/** * Validate the given stream and return a valid DOM document for parsing. */ protected Document buildDocument(ErrorHandler handler, InputStream stream) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder parser = dbf.newDocumentBuilder(); parser.setErrorHandler(handler); return parser.parse(stream); }
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; }
/** * Parse the supplied XML stream data to a {@link Document}. * <p> * This function does not close the stream. * * @param stream The XML stream. * @return The XML {@link Document}. * @throws SAXException Error parsing the XML stream data e.g. badly formed XML. * @throws IOException Error reading from the steam. * @since 2.0 */ public static @Nonnull Document parse(@Nonnull Reader stream) throws SAXException, IOException { DocumentBuilder docBuilder; try { docBuilder = newDocumentBuilderFactory().newDocumentBuilder(); docBuilder.setEntityResolver(RestrictiveEntityResolver.INSTANCE); } catch (ParserConfigurationException e) { throw new IllegalStateException("Unexpected error creating DocumentBuilder.", e); } return docBuilder.parse(new InputSource(stream)); }
/** * Create a JAXP DocumentBuilder that this bean definition reader * will use for parsing XML documents. Can be overridden in subclasses, * adding further initialization of the builder. * @param factory the JAXP DocumentBuilderFactory that the DocumentBuilder * should be created with * @param entityResolver the SAX EntityResolver to use * @param errorHandler the SAX ErrorHandler to use * @return the JAXP DocumentBuilder * @throws ParserConfigurationException if thrown by JAXP methods */ protected DocumentBuilder createDocumentBuilder(DocumentBuilderFactory factory, @Nullable EntityResolver entityResolver, @Nullable ErrorHandler errorHandler) throws ParserConfigurationException { DocumentBuilder docBuilder = factory.newDocumentBuilder(); if (entityResolver != null) { docBuilder.setEntityResolver(entityResolver); } if (errorHandler != null) { docBuilder.setErrorHandler(errorHandler); } return docBuilder; }
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); docBuilder.setEntityResolver((publicId, systemId) -> { return new InputSource(new StringReader("")); }); Document doc = docBuilder.parse(svgFontFile); doc.getDocumentElement().normalize(); NodeList glyphsList = doc.getElementsByTagName("glyph"); for (int i = 0; i < glyphsList.getLength(); i++) { Node glyph = glyphsList.item(i); Node glyphName = glyph.getAttributes().getNamedItem("glyph-name"); if (glyphName == null) { continue; String glyphId = glyphName.getNodeValue(); SVGGlyphBuilder glyphPane = new SVGGlyphBuilder(i, glyphId, glyph.getAttributes() .getNamedItem("d") .getNodeValue());
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 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); } }
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); } } }
BufferedInputStream input = null; try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); input = new BufferedInputStream(new FileInputStream(xmlConfigFile)); InputSource source = new InputSource(input); factory.setNamespaceAware(false); factory.setValidating(false); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setEntityResolver(new EntityResolver() { @Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { return new InputSource(); Document document = builder.parse(source); NodeList issues = document.getElementsByTagName(TAG_ISSUE); for (int i = 0, count = issues.getLength(); i < count; i++) { Node node = issues.item(i); String id = element.getAttribute(ATTR_ID); if (id.length() == 0) { System.err.println("Invalid config file: Missing required issue id attribute");
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 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();
HttpResponse response = client.execute(post); HttpEntity r_entity = response.getEntity(); String xmlString = EntityUtils.toString(r_entity); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder db = factory.newDocumentBuilder(); InputSource inStream = new InputSource(); inStream.setCharacterStream(new StringReader(xmlString)); Document doc = db.parse(inStream); String playcount = "empty"; NodeList nl = doc.getElementsByTagName("playcount"); for(int i = 0; i < nl.getLength(); i++) { if (nl.item(i).getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) { org.w3c.dom.Element nameElement = (org.w3c.dom.Element) nl.item(i); playcount = nameElement.getFirstChild().getNodeValue().trim(); } }
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); }
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);
private void compileMappingFiles(List<String> mappingFiles, byte[] sourceArray) throws IOException, ParserConfigurationException, SAXException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); // Disable DTDs to prevent XXE attack dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); DocumentBuilder parser = dbf.newDocumentBuilder(); parser.setErrorHandler(handler); Document dom = parser.parse(new ByteArrayInputStream(sourceArray)); NodeList nodes = dom.getElementsByTagName("/persistence/persistence-unit/mapping-file"); if (nodes != null && nodes.getLength() > 0) { int length = nodes.getLength(); for (int j=0;j<length;j++){ Node node = nodes.item(j); mappingFiles.add(node.getNodeValue()); } } } }
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()); } } }
//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); }
/** * 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; }
@Test public void testNamespace() throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder docBuilder = factory.newDocumentBuilder(); Document doc = docBuilder.parse(new InputSource(new StringReader(maryxmlString))); assertNotNull(doc.getDocumentElement().getNamespaceURI()); Document doc2 = docBuilder.parse(this.getClass().getResourceAsStream("test1.maryxml")); assertNotNull(doc2.getDocumentElement().getNamespaceURI()); } }