Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Creating a Java DOM XML parser is done using the javax.xml.parsers.DocumentBuilderFactory class. Here is an example:</p> <pre><code>DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = null; try { builder = builderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); } </code></pre> <p>Parsing an XML file into a DOM tree using the DocumentBuilder is done like this:</p> <pre><code>try { Document document = builder.parse( new FileInputStream("data\\text.xml")); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } </code></pre> <p>At the top is the Document object. The Document object has a single root element, which is returned by calling getDocumentElement() like this:</p> <pre><code>Element rootElement = document.getDocumentElement(); </code></pre> <p>get the children of an element</p> <pre><code>NodeList nodes = element.getChildNodes(); for(int i=0; i&lt;nodes.getLength(); i++){ Node node = nodes.item(i); if(node instanceof Element){ //a child element to process Element child = (Element) node; String attribute = child.getAttribute("width"); } } </code></pre> <p>Now you have a needed Node, so you can create put it in map as you wish, and make need for you key. method transformer.transform(new DOMSource(document),work with any Dom node or element</p> <p>Create String from Document</p> <pre><code>TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); StringWriter buffer = new StringWriter(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.transform(new DOMSource(document), new StreamResult(buffer)); String str = buffer.toString(); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload