public static Element parseElement(String xml) { try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbFactory.newDocumentBuilder(); Document doc = docBuilder.parse(new ByteArrayInputStream(xml.getBytes())); return doc.getDocumentElement(); } catch (Exception e) { throw new RuntimeException(e); } }
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setIgnoringComments(true); DocumentBuilder builder = domFactory.newDocumentBuilder(); Document doc = builder.parse(new File("XmlTest.xml")); NodeList nodes = doc.getElementsByTagName("CustomerId"); Text a = doc.createTextNode("value"); Element p = doc.createElement("newNode"); p.appendChild(a); nodes.item(0).getParentNode().insertBefore(p, nodes.item(0));
private Document initDocument() throws IOException { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder; try { documentBuilder = documentBuilderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new IOException("Failed to create settings document builder", e); } Document document = documentBuilder.newDocument(); Element settingsElement = document.createElement(SCHEMA_DOCUMENT_ELEMENT); settingsElement.setAttribute(SCHEMA_MODEL_VERSION, "" + getRevisionNumber()); document.appendChild(settingsElement); return document; }
private Element createTextElement(String name, String value) { Element element = document.createElementNS(RULESET_2_0_0_NS_URI, name); Text text = document.createTextNode(value); element.appendChild(text); return element; }
private Element createCDATASectionElement(String name, String value) { Element element = document.createElementNS(RULESET_2_0_0_NS_URI, name); CDATASection cdataSection = document.createCDATASection(value); element.appendChild(cdataSection); return element; } }
private Element appendElement(Element parent, String name, String text) { Document document = parent.getOwnerDocument(); Element child = document.createElement(name); parent.appendChild(child); if (text != null) { Text textNode = document.createTextNode(text); child.appendChild(textNode); } return child; }
public KlattDurationParams(String filename) throws SAXException, IOException, ParserConfigurationException { // parse the xml file: DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(new File(filename)); // In document, ignore everything that is not a segment element: NodeList segElements = document.getElementsByTagName("segment"); for (int i = 0; i < segElements.getLength(); i++) { Element seg = (Element) segElements.item(i); String name = seg.getAttribute("s"); int inherentDuration = Integer.parseInt(seg.getAttribute("inh")); int minimalDuration = Integer.parseInt(seg.getAttribute("min")); inh.put(name, inherentDuration); min.put(name, minimalDuration); } }
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 + ">"); } }
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");
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); } }
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();
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 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 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()); } } }
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);
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()); } } }
/** * Returns the text content of all nodes in the given file with the given tag. * If the text contents contains embedded tags, strips the embedded tags out * of the returned text. E.g., {@code <s>This is a <s>sentence</s> with embedded tags * </s>} would return the list containing ["This is a sentence with embedded * tags", "sentence"]. * * @throws SAXException if tag doesn't exist in the file. * @return List of String text contents of tags. */ private static List<Element> getTagElementsFromFileSAXException( File f, String tag) throws SAXException { List<Element> sents = Generics.newArrayList(); try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(f); doc.getDocumentElement().normalize(); NodeList nodeList=doc.getElementsByTagName(tag); for (int i = 0; i < nodeList.getLength(); i++) { // Get element Element element = (Element)nodeList.item(i); sents.add(element); } } catch (IOException | ParserConfigurationException e) { log.warn(e); } return sents; }
//obtain Document somehow, doesn't matter how DocumentBuilder b = DocumentBuilderFactory.newInstance().newDocumentBuilder(); org.w3c.dom.Document doc = b.parse(new FileInputStream("page.html")); //Evaluate XPath against Document itself XPath xPath = XPathFactory.newInstance().newXPath(); NodeList nodes = (NodeList)xPath.evaluate("/html/body/p/div[3]/a", doc.getDocumentElement(), XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); ++i) { Element e = (Element) nodes.item(i); }
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 static String getTagAttributeText(final Document doc, final String tag, final String attribute) { NodeList elementsByTagName = doc.getElementsByTagName(tag); for (int i = 0; i < elementsByTagName.getLength(); ++i) { Node item = elementsByTagName.item(i); Node namedItem = item.getAttributes().getNamedItem(attribute); if (namedItem != null) { return namedItem.getTextContent(); } } return null; }