public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, TransformerException { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory .newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document document = docBuilder.parse(new File("document.xml")); NodeList nodeList = document.getElementsByTagName("*"); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { // do something with the current element System.out.println(node.getNodeName()); } } }
import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.NodeList; public class Demo { public static void main(String[] args) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(new File("input.xml")); NodeList nodeList = document.getElementsByTagName("Item"); for(int x=0,size= nodeList.getLength(); x<size; x++) { System.out.println(nodeList.item(x).getAttributes().getNamedItem("name").getNodeValue()); } } }
/** If the child node or attribute doesn't exist, it is created. Usage example: Node property = * getFirstChildByAttrValue(properties, "property", "name"); */ private static Node getFirstChildByNameAttrValue (Node node, String childName, String attr, String value) { NodeList childNodes = node.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { if (childNodes.item(i).getNodeName().equals(childName)) { NamedNodeMap attributes = childNodes.item(i).getAttributes(); Node attribute = attributes.getNamedItem(attr); if (attribute.getNodeValue().equals(value)) return childNodes.item(i); } } Node newNode = node.getOwnerDocument().createElement(childName); NamedNodeMap attributes = newNode.getAttributes(); Attr nodeAttr = node.getOwnerDocument().createAttribute(attr); nodeAttr.setNodeValue(value); attributes.setNamedItem(nodeAttr); if (childNodes.item(0) != null) { return node.insertBefore(newNode, childNodes.item(0)); } else { return node.appendChild(newNode); } }
/** * Matches the given node's name and local name against the given desired name. */ private static boolean nodeNameMatch(Node node, String desiredName) { return (desiredName.equals(node.getNodeName()) || desiredName.equals(node.getLocalName())); }
private static String extractNameAttribute(Node node) { return node.getAttributes().getNamedItem("name").getNodeValue(); }
private void parse(Document doc) { NodeList nodeList = doc.getChildNodes(); for (int count = 0; count < nodeList.getLength(); count++) { Node node = nodeList.item(count); if (node.getNodeType() == Node.ELEMENT_NODE && node.hasChildNodes()) { parseAttrList(node.getChildNodes()); } } }
private static void parseProperties(NodeList nodeList, RootBeanDefinition beanDefinition) { if (nodeList != null && nodeList.getLength() > 0) { for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node instanceof Element) { if ("property".equals(node.getNodeName()) || "property".equals(node.getLocalName())) { String name = ((Element) node).getAttribute("name"); if (name != null && name.length() > 0) { String value = ((Element) node).getAttribute("value"); String ref = ((Element) node).getAttribute("ref"); if (value != null && value.length() > 0) { beanDefinition.getPropertyValues().addPropertyValue(name, value); } else if (ref != null && ref.length() > 0) { beanDefinition.getPropertyValues().addPropertyValue(name, new RuntimeBeanReference(ref)); } else { throw new UnsupportedOperationException("Unsupported <property name=\"" + name + "\"> sub tag, Only supported <property name=\"" + name + "\" ref=\"...\" /> or <property name=\"" + name + "\" value=\"...\" />"); } } } } } } }
private AndroidManifest parse(File androidManifestFile, boolean libraryProject) throws AndroidManifestNotFoundException { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); doc = docBuilder.parse(androidManifestFile); } catch (Exception e) { LOGGER.error("Could not parse the AndroidManifest.xml file at path {}", androidManifestFile, e); Element documentElement = doc.getDocumentElement(); documentElement.normalize(); String applicationPackage = documentElement.getAttribute("package"); boolean applicationDebuggableMode = false; if (applicationNodes.getLength() > 0) { Node applicationNode = applicationNodes.item(0); Node nameAttribute = applicationNode.getAttributes().getNamedItem("android:name"); LOGGER.warn("The class application declared in the AndroidManifest.xml cannot be found in the compile path: [{}]", nameAttribute.getNodeValue()); Node debuggableAttribute = applicationNode.getAttributes().getNamedItem("android:debuggable"); if (debuggableAttribute != null) { applicationDebuggableMode = debuggableAttribute.getNodeValue().equalsIgnoreCase("true");
protected void parseRules(InputStream input) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); // for now DocumentBuilder builder=factory.newDocumentBuilder(); Document document=builder.parse(input); Element root=document.getDocumentElement(); match(RULES, root.getNodeName(), true); NodeList children=root.getChildNodes(); if(children == null || children.getLength() == 0) return; for(int i=0; i < children.getLength(); i++) { Node node=children.item(i); if(node.getNodeType() != Node.ELEMENT_NODE) continue; String element_name=node.getNodeName(); if(RULE.equals(element_name)) parseRule(node); else throw new Exception("expected <" + RULE + ">, but got " + "<" + element_name + ">"); } }
public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, TransformerException { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory .newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document document = docBuilder.parse(new File("document.xml")); doSomething(document.getDocumentElement()); } public static void doSomething(Node node) { // do something with the current node instead of System.out System.out.println(node.getNodeName()); NodeList nodeList = node.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Node currentNode = nodeList.item(i); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { //calls this method for all the children which is Element doSomething(currentNode); } } }
private void initData () throws ParserConfigurationException, IOException, SAXException { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = dbFactory.newDocumentBuilder(); Document doc = builder.parse(ExternalExtensionsDialog.class .getResourceAsStream("/com/badlogic/gdx/setup/data/extensions.xml")); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName("extension"); for (int i = 0; i < nList.getLength(); i++) { Node nNode = nList.item(i); if (nNode.getNodeType() == Node.ELEMENT_NODE) { String name = eElement.getElementsByTagName("name").item(0).getTextContent(); String description = eElement.getElementsByTagName("description").item(0).getTextContent(); String version = eElement.getElementsByTagName("version").item(0).getTextContent(); String compatibility = eElement.getElementsByTagName("compatibility").item(0).getTextContent(); String url = eElement.getElementsByTagName("website").item(0).getTextContent(); for (int j = 0; j < inheritsNode.getLength(); j++) gwtInherits[j] = inheritsNode.item(j).getTextContent();
private void parse() throws ParserException { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); Document document; try { DocumentBuilder builder = builderFactory.newDocumentBuilder(); builder.setEntityResolver(new EntityResolver() { @Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { document = builder.parse(new ByteArrayInputStream(xml.getBytes("UTF-8"))); Node manifestNode = document.getElementsByTagName("manifest").item(0); NodeList nodes = manifestNode.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); String nodeName = node.getNodeName(); if (nodeName.equals("application")) { NodeList children = node.getChildNodes(); for (int j = 0; j < children.getLength(); j++) { Node child = children.item(j); String childName = child.getNodeName(); switch (childName) { case "service": break; case "meta-data": NamedNodeMap attributes = child.getAttributes(); metaDatas.put(getAttribute(attributes, "android:name"), getAttribute(attributes, "android:value")); break;
private static Source mergeIntoSource(InputStream baseXmlStream, InputStream xmlStream) throws Exception { DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setIgnoringComments(true); domFactory.setValidating(false); domFactory.setNamespaceAware(true); DocumentBuilder builder = domFactory.newDocumentBuilder(); Document baseDoc = builder.parse(baseXmlStream); Document ruleDoc = builder.parse(xmlStream); // Shall this be more generic, i.e. reuse not just unification ??? NodeList unificationNodes = baseDoc.getElementsByTagName("unification"); Node ruleNode = ruleDoc.getElementsByTagName("rules").item(0); Node firstChildRuleNode = ruleNode.getChildNodes().item(1); for (int i = 0; i < unificationNodes.getLength(); i++) { Node unificationNode = ruleDoc.importNode(unificationNodes.item(i), true); ruleNode.insertBefore(unificationNode, firstChildRuleNode); } return new DOMSource(ruleDoc); }
public String getSample( String strFunctionName, String strFunctionNameWithArgs ) { String sRC = "// Sorry, no Script available for " + strFunctionNameWithArgs; NodeList nl = dom.getElementsByTagName( "jsFunction" ); for ( int i = 0; i < nl.getLength(); i++ ) { if ( nl.item( i ).getAttributes().getNamedItem( "name" ).getNodeValue().equals( strFunctionName ) ) { Node elSample = ( (Element) nl.item( i ) ).getElementsByTagName( "sample" ).item( 0 ); if ( elSample.hasChildNodes() ) { return ( elSample.getFirstChild().getNodeValue() ); } } } return sRC; }
@Test public void testXMLParserSupportsNamespaces() throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder docBuilder = factory.newDocumentBuilder(); Document document = docBuilder.parse(this.getClass().getResourceAsStream("test1.namespaces")); NodeList nl = document.getElementsByTagNameNS("http://www.w3.org/2001/10/synthesis", "*"); assertNotNull(nl.item(0)); assertTrue(nl.item(0).getNodeName().equals("ssml:emphasis")); }
protected static List<Triple<Short,String,Boolean>> parse(InputStream stream) throws Exception { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); factory.setValidating(false); // for now DocumentBuilder builder=factory.newDocumentBuilder(); Document document=builder.parse(stream); NodeList class_list=document.getElementsByTagName("class"); List<Triple<Short,String,Boolean>> list=new LinkedList<>(); for(int i=0; i < class_list.getLength(); i++) { if(class_list.item(i).getNodeType() == Node.ELEMENT_NODE) { list.add(parseClassData(class_list.item(i))); } } return list; }
private void parseAttrList(NodeList nodeList) { for (int count = 0; count < nodeList.getLength(); count++) { Node tempNode = nodeList.item(count); if (tempNode.getNodeType() == Node.ELEMENT_NODE && tempNode.hasAttributes() && tempNode.hasChildNodes()) { String name = null; NamedNodeMap nodeMap = tempNode.getAttributes(); for (int i = 0; i < nodeMap.getLength(); i++) { Node node = nodeMap.item(i); if (node.getNodeName().equals("name")) { name = node.getNodeValue(); break; } } if (name != null && tempNode.getNodeName().equals("attr")) { parseValues(name, tempNode.getChildNodes()); } else { parseAttrList(tempNode.getChildNodes()); } } } }
private static String getDependencyManagementPluginVersion() { try (FileReader pomReader = new FileReader("pom.xml")) { Document pom = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(new InputSource(pomReader)); NodeList dependencyElements = pom.getElementsByTagName("dependency"); for (int i = 0; i < dependencyElements.getLength(); i++) { Element dependency = (Element) dependencyElements.item(i); if (dependency.getElementsByTagName("artifactId").item(0).getTextContent() .equals("dependency-management-plugin")) { return dependency.getElementsByTagName("version").item(0).getTextContent(); } } throw new IllegalStateException("dependency management plugin version not found"); } catch (Exception ex) { throw new IllegalStateException("Failed to find dependency management plugin version", ex); } }
public static List<Person> readXMLCharacterList(Document doc) { List<Person> personList = new ArrayList<>(); NodeList characters = doc.getDocumentElement().getElementsByTagName("characters").item(0).getChildNodes(); for(int i = 0; i < characters.getLength(); i++) { Node child = characters.item(i); if(child.getNodeName().equals("character")) { String name = child.getAttributes().getNamedItem("name").getNodeValue(); char[] cName = name.toCharArray(); cName[0] = Character.toUpperCase(cName[0]); name = new String(cName); List<String> aliases = Arrays.asList(child.getAttributes().getNamedItem("aliases").getNodeValue().split(";")); String gender = (child.getAttributes().getNamedItem("gender") == null) ? "" : child.getAttributes().getNamedItem("gender").getNodeValue(); personList.add(new Person(child.getAttributes().getNamedItem("name").getNodeValue(), gender, aliases)); } } return personList; } //write the character list to a file to work with the annotator
public static void combineAllApplyTags(Document document) { NodeList nl = document.getElementsByTagName("apply"); while(nl.getLength() > 0) { Element app = (Element) nl.item(0); Element parent = (Element) app.getParentNode(); NamedNodeMap attrs = app.getAttributes(); for(int i = 0; i < attrs.getLength(); i++) { Node ns = attrs.item(i); parent.setAttribute(ns.getNodeName(), ns.getNodeValue()); } while(app.getChildNodes().getLength() > 0) { Node ni = app.getChildNodes().item(0); app.getParentNode().insertBefore(ni, app); } app.getParentNode().removeChild(app); } }