List of usage examples for org.w3c.dom Document getElementsByTagName
public NodeList getElementsByTagName(String tagname);
NodeList
of all the Elements
in document order with a given tag name and are contained in the document. From source file:org.ale.scanner.zotero.web.zotero.ZoteroAPIClient.java
public static Access parsePermissions(String resp, Account user) { /* example:/*from w ww . ja va 2 s .c om*/ <key key="xxx"> <access library="1" files="1" notes="1" write="1"/> <access group="12345" write="1"/> <access group="all" write="1"/> </key> */ Document doc = ZoteroAPIClient.parseXML(resp); if (doc == null) return null; NodeList keys = doc.getElementsByTagName("key"); if (keys.getLength() == 0) return null; Node keyNode = keys.item(0); Node keyAttr = keyNode.getAttributes().getNamedItem("key"); if (keyAttr == null) return null; String key = keyAttr.getNodeValue(); if (!key.equals(user.getKey())) return null; NodeList accessTags = doc.getElementsByTagName("access"); int[] groups = new int[accessTags.getLength()]; int[] permissions = new int[accessTags.getLength()]; for (int i = 0; i < accessTags.getLength(); i++) { permissions[i] = Access.READ; NamedNodeMap attr = accessTags.item(i).getAttributes(); Node groupNode = attr.getNamedItem("group"); if (groupNode == null) { // Library access? groupNode = attr.getNamedItem("library"); if (groupNode == null) return null; groups[i] = Group.GROUP_LIBRARY; } else { // Individual group or all groups if (groupNode.getNodeValue().equals("all")) groups[i] = Group.GROUP_ALL; else groups[i] = Integer.parseInt(groupNode.getNodeValue()); } Node writeNode = attr.getNamedItem("write"); if (writeNode != null && writeNode.getNodeValue().equals("1")) { permissions[i] |= Access.WRITE; } Node noteNode = attr.getNamedItem("notes"); if (noteNode != null && noteNode.getNodeValue().equals("1")) { permissions[i] |= Access.NOTE; } } return new Access(user.getDbId(), groups, permissions); }
From source file:com.sun.socialsite.pojos.App.java
public static App readFromStream(InputStream in, URL urlToStore) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(in); in.close();//from w w w . jav a2s. co m App app = new App(); app.setURL(urlToStore); Element modulePrefsElement = (Element) (doc.getElementsByTagName("ModulePrefs").item(0)); app.setAuthor(modulePrefsElement.getAttribute("author")); app.setAuthorEmail(modulePrefsElement.getAttribute("author_email")); if (!"".equals(modulePrefsElement.getAttribute("author_link"))) { app.setAuthorLink(new URL(urlToStore, modulePrefsElement.getAttribute("author_link"))); } app.setDescription(modulePrefsElement.getAttribute("description")); app.setDirectoryTitle(modulePrefsElement.getAttribute("directory_title")); if (!"".equals(modulePrefsElement.getAttribute("height"))) { app.setHeight(Integer.parseInt(modulePrefsElement.getAttribute("height"))); } if (!"".equals(modulePrefsElement.getAttribute("show_in_directory"))) { app.setShowInDirectory(Boolean.valueOf(modulePrefsElement.getAttribute("show_in_directory"))); } if (!"".equals(modulePrefsElement.getAttribute("scrolling"))) { app.setScrolling(Boolean.valueOf(modulePrefsElement.getAttribute("scrolling"))); } if (!"".equals(modulePrefsElement.getAttribute("singleton"))) { app.setSingleton(Boolean.valueOf(modulePrefsElement.getAttribute("singleton"))); } if (!"".equals(modulePrefsElement.getAttribute("thumbnail"))) { app.setThumbnail(new URL(urlToStore, modulePrefsElement.getAttribute("thumbnail"))); } app.setTitle(modulePrefsElement.getAttribute("title")); if (!"".equals(modulePrefsElement.getAttribute("title_url"))) { app.setTitleURL(new URL(urlToStore, modulePrefsElement.getAttribute("title_url"))); } if (!"".equals(modulePrefsElement.getAttribute("width"))) { app.setWidth(Integer.parseInt(modulePrefsElement.getAttribute("width"))); } return app; }
From source file:com.wavemaker.tools.pws.install.PwsInstall.java
public static Document insertImport(Document doc, String resource) { List<Node> targetList = new ArrayList<Node>(); // First, delete old lines if any. NodeList list = doc.getElementsByTagName("import"); Node node = null;//w ww . j a va 2s.co m for (int i = 0; i < list.getLength(); i++) { node = list.item(i); NamedNodeMap attributes = node.getAttributes(); for (int j = 0; j < attributes.getLength(); j++) { Node attr = attributes.item(j); if (attr.getNodeName().equals("resource") && attr.getNodeValue().equals(resource)) { targetList.add(node); break; } } } NodeList beans_list = doc.getElementsByTagName("beans"); Node beans_node = beans_list.item(0); if (targetList.size() > 0) { for (Node target : targetList) { beans_node.removeChild(target); } } // Now, add the new line NodeList list1 = beans_node.getChildNodes(); Node bean_node = null; for (int i = 0; i < list1.getLength(); i++) { Node node1 = list1.item(i); if (node1.getNodeName().equals("bean")) { bean_node = node1; break; } } Element elem = doc.createElement("import"); elem.setAttribute("resource", resource); try { if (bean_node != null) { beans_node.insertBefore(elem, bean_node); } else { beans_node.appendChild(elem); } } catch (DOMException ex) { ex.printStackTrace(); } return doc; }
From source file:org.shareok.data.documentProcessor.DocumentProcessorUtil.java
/** * * @param filePath : file path/*from ww w .ja va 2 s . c o m*/ * @param tagName : tag name * @param attributeMap : the map of attribute name-value map. Note: no null value contained in this map * @return : value of the elements */ public static String[] getDataFromXmlByTagNameAndAttributes(String filePath, String tagName, Map<String, String> attributeMap) { String[] data = null; try { File file = new File(filePath); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(file); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName(tagName); int length = nList.getLength(); if (length == 0) { return null; } List<String> dataList = new ArrayList<>(); for (int temp = 0; temp < length; temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { boolean attrMatched = true; Element eElement = (Element) nNode; for (String att : attributeMap.keySet()) { String val = attributeMap.get(att); if (!eElement.hasAttribute(att) || !val.equals(eElement.getAttribute(att))) { attrMatched = false; } } if (attrMatched == true) { dataList.add(eElement.getTextContent()); } } } int size = dataList.size(); data = new String[size]; data = dataList.toArray(data); } catch (ParserConfigurationException | SAXException | IOException | DOMException ex) { logger.error("Cannot get the data from file at " + filePath + " by tag name " + tagName + " and attributes map", ex); } return data; }
From source file:com.google.enterprise.adaptor.experimental.Sim.java
/** Find all record urls in Adaptor created XML metadata-and-url feed file. */ static Set<URL> extractUrls(String xml) throws SAXException, ParserConfigurationException, BadFeed { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); /* to avoid blowing up on doctype line: * http://stackoverflow.com/questions/155101/make-documentbuilder-parse-ignore-dtd-references */ dbf.setValidating(false);/*w w w .j av a 2 s.com*/ dbf.setFeature("http://xml.org/sax/features/namespaces", false); dbf.setFeature("http://xml.org/sax/features/validation", false); dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); DocumentBuilder db = dbf.newDocumentBuilder(); InputStream xmlStream = new ByteArrayInputStream(xml.getBytes(UTF8)); Document doc; try { doc = db.parse(xmlStream); } catch (IOException ie) { throw new BadFeed(ie.getMessage()); } doc.getDocumentElement().normalize(); NodeList nodes = doc.getElementsByTagName("record"); Set<URL> tmpUrls = new HashSet<URL>(); for (int i = 0; i < nodes.getLength(); i++) { Element element = (Element) nodes.item(i); String url = element.getAttribute("url"); if (null == url || url.trim().isEmpty()) { throw new BadFeed("record without url attribute"); } else { try { tmpUrls.add(new URL(url)); } catch (MalformedURLException male) { throw new BadFeed("record with bad url attribute: " + url); } } log.info("accepting url: " + url); } return tmpUrls; }
From source file:org.apache.ofbiz.passport.user.LinkedInAuthenticator.java
public static Map<String, String> parseLinkedInUserInfo(Document userInfo) { Map<String, String> results = new HashMap<String, String>(); NodeList persons = userInfo.getElementsByTagName("person"); if (UtilValidate.isEmpty(persons) || persons.getLength() <= 0) { return results; }// w ww . ja v a 2 s. c o m Element person = (Element) persons.item(0); Element standardProfileRequest = UtilXml.firstChildElement(person, "site-standard-profile-request"); Element url = UtilXml.firstChildElement(standardProfileRequest, "url"); if (UtilValidate.isNotEmpty(url)) { String urlContent = url.getTextContent(); if (UtilValidate.isNotEmpty(urlContent)) { String id = urlContent.substring(urlContent.indexOf("?id=")); id = id.substring(0, id.indexOf("&")); Debug.logInfo("LinkedIn user id: " + id, module); results.put("userId", id); } } Element firstNameElement = UtilXml.firstChildElement(person, "first-name"); if (UtilValidate.isNotEmpty(firstNameElement) && UtilValidate.isNotEmpty(firstNameElement.getTextContent())) { results.put("firstName", firstNameElement.getTextContent()); } Element lastNameElement = UtilXml.firstChildElement(person, "last-name"); if (UtilValidate.isNotEmpty(lastNameElement) && UtilValidate.isNotEmpty(lastNameElement.getTextContent())) { results.put("lastName", lastNameElement.getTextContent()); } Element emailElement = UtilXml.firstChildElement(person, "email-address"); if (UtilValidate.isNotEmpty(emailElement) && UtilValidate.isNotEmpty(emailElement.getTextContent())) { results.put("emailAddress", emailElement.getTextContent()); } return results; }
From source file:org.ale.scanner.zotero.web.zotero.ZoteroAPIClient.java
public static Group[] parseGroups(String resp) { /* example:/*from w ww .ja va 2 s. c o m*/ <!-- tons of garbage --> <zapi:totalResults>1</zapi:totalResults> <zapi:apiVersion>1</zapi:apiVersion> <updated>2011-07-15T22:46:21Z</updated> <entry xmlns:zxfer="http://zotero.org/ns/transfer"> <title>group title</title> <author> <name>some_user</name> <uri>http://zotero.org/some_user</uri> </author> <id>http://zotero.org/groups/12345</id> <published>2011-07-15T22:46:01Z</published> <updated>2011-07-15T22:46:21Z</updated> <link rel="self" type="application/atom+xml" href="https://api.zotero.org/groups/12345"/> <link rel="alternate" type="text/html" href="http://zotero.org/groups/12345"/> <zapi:numItems>10</zapi:numItems> <content type="html"> <!-- more garbage --> </content> </entry> */ /* Returns null for parsing errors */ Document doc = ZoteroAPIClient.parseXML(resp); if (doc == null) return null; NodeList totalResults = doc.getElementsByTagName("zapi:totalResults"); if (totalResults.getLength() == 0) return null; String trStr = totalResults.item(0).getFirstChild().getNodeValue(); if (trStr == null || !TextUtils.isDigitsOnly(trStr)) return null; int numGroups = Integer.parseInt(trStr); Group[] groups = new Group[numGroups]; NodeList entries = doc.getElementsByTagName("entry"); if (entries.getLength() != numGroups) return null; for (int i = 0; i < numGroups; i++) { if (entries.item(i).getNodeType() != Node.ELEMENT_NODE) return null; NodeList titles = ((Element) entries.item(i)).getElementsByTagName("title"); NodeList ids = ((Element) entries.item(i)).getElementsByTagName("id"); if (titles.getLength() != 1 || ids.getLength() != 1) return null; String title = titles.item(0).getFirstChild().getNodeValue(); String idUri = ids.item(0).getFirstChild().getNodeValue(); if (title == null || idUri == null) return null; int lastSeg = idUri.lastIndexOf("/"); if (lastSeg < 0) return null; String idstr = idUri.substring(lastSeg + 1); if (!TextUtils.isDigitsOnly(idstr)) return null; int id = Integer.parseInt(idstr); groups[i] = new Group(id, title); } return groups; }
From source file:org.ale.scanner.zotero.web.zotero.ZoteroAPIClient.java
public static String parseItems(String resp) { /* example:// www. j a v a2s. co m <!-- tons of garbage --> <zapi:totalResults>1</zapi:totalResults> <zapi:apiVersion>1</zapi:apiVersion> <updated>2010-12-17T00:18:51Z</updated> <entry> <title>My Book</title> <author> <name>Zotero User</name> <uri>http://zotero.org/zuser</uri> </author> <id>http://zotero.org/users/zuser/items/ABCD2345</id> <published>2010-12-17T00:18:51Z</published> <updated>2010-12-17T00:18:51Z</updated> <link rel="self" type="application/atom+xml" href="https://api.zotero.org/users/1/items/ABCD2345?content=json"/> <link rel="alternate" type="text/html" href="http://zotero.org/users/zuser/items/ABCD2345"/> <zapi:key>ABCD2345</zapi:key> <zapi:itemType>book</zapi:itemType> <zapi:creatorSummary>McAuthor</zapi:creatorSummary> <zapi:numChildren>1</zapi:numChildren> <zapi:numTags>2</zapi:numTags> <content type="application/json" etag="8e984e9b2a8fb560b0085b40f6c2c2b7"> { "itemType" : "book", "title" : "My Book", "creators" : [ { "creatorType" : "author", "firstName" : "Sam", "lastName" : "McAuthor" }, { "creatorType":"editor", "name" : "John T. Singlefield" } ], "tags" : [ { "tag" : "awesome" }, { "tag" : "rad", "type" : 1 } ] } </content> </entry> </feed> */ /* Returns null for parsing errors */ Document doc = ZoteroAPIClient.parseXML(resp); if (doc == null) return null; NodeList totalResults = doc.getElementsByTagName("zapi:totalResults"); if (totalResults.getLength() == 0) return null; String trStr = totalResults.item(0).getFirstChild().getNodeValue(); if (trStr == null || !TextUtils.isDigitsOnly(trStr)) return null; int numGroups = Integer.parseInt(trStr); Group[] groups = new Group[numGroups]; NodeList entries = doc.getElementsByTagName("entry"); if (entries.getLength() != numGroups) return null; for (int i = 0; i < numGroups; i++) { if (entries.item(i).getNodeType() != Node.ELEMENT_NODE) return null; NodeList titles = ((Element) entries.item(i)).getElementsByTagName("title"); NodeList ids = ((Element) entries.item(i)).getElementsByTagName("id"); if (titles.getLength() != 1 || ids.getLength() != 1) return null; String title = titles.item(0).getFirstChild().getNodeValue(); String idUri = ids.item(0).getFirstChild().getNodeValue(); if (title == null || idUri == null) return null; int lastSeg = idUri.lastIndexOf("/"); if (lastSeg < 0) return null; String idstr = idUri.substring(lastSeg + 1); if (!TextUtils.isDigitsOnly(idstr)) return null; int id = Integer.parseInt(idstr); groups[i] = new Group(id, title); } return ""; }
From source file:org.jboss.as.test.integration.logging.formatters.XmlFormatterTestCase.java
private static void validateStackTrace(final Document doc, final boolean validateFormatted, final boolean validateStructured) { if (validateFormatted) { Assert.assertTrue(doc.getElementsByTagName("stackTrace").getLength() > 0); } else {//from w w w .ja v a 2 s. c o m Assert.assertEquals(0, doc.getElementsByTagName("stackTrace").getLength()); } if (validateStructured) { final NodeList exceptions = doc.getElementsByTagName("exception"); Assert.assertTrue(exceptions.getLength() > 0); validateStackTrace(exceptions.item(0)); } else { Assert.assertEquals(0, doc.getElementsByTagName("exception").getLength()); } }
From source file:com.vmware.qe.framework.datadriven.utils.XMLUtil.java
/** * Get child nodes of the first element that has the specified tag name and also contains the * specified attribute id and value//from w w w.j a va 2s . com * * @param xmlFile XML file contents * @param elementName name of the required element * @param attrId Id of an attribute in element * @param attrVal attribute value for the given attribute * @return NodeList childNodes if the given element name with the given attributeId and * attributeValue exists, otherwise null * @throws Exception */ public static NodeList getChildNodes(String xmlFile, String elementName, String attrId, String attrVal) throws Exception { NodeList childNodes = null; Document xmlDoc = getXmlDocumentElement(xmlFile); NodeList elements = xmlDoc.getElementsByTagName(elementName); for (int i = 0; i < elements.getLength(); i++) { Element element = (Element) elements.item(i); if (element.hasAttribute(attrId)) { if (element.getAttribute(attrId).equals(attrVal)) { childNodes = element.getChildNodes(); break; } } } return childNodes; }