JAVA XML : get content Node

Younes Sassi :

I have an xml like this :

<root>
   <countries>
      <country id="98" nom="Espagne"/>
      <country id="76" nom="France"/>
   </countries>
</root>

I can read inside root tag with this :

Document doc = DocumentBuilderFactory.newInstance()
                    .newDocumentBuilder().parse(XmlFile);

System.out.println("Root element :" + doc.getDocumentElement().getNodeName());      

Node NodeCountries = doc.getElementsByTagName("countries").item(0);     

System.out.println(nodeToString(NodeCountries));


private static String nodeToString(Node node) throws Exception{
            StringWriter sw = new StringWriter();

              Transformer t = TransformerFactory.newInstance().newTransformer();
              t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
              t.setOutputProperty(OutputKeys.INDENT, "yes");
              t.transform(new DOMSource(node), new StreamResult(sw));

            return sw.toString();
          }

But I can not get all content inside countries tag like this :

<country id="98" nom="Espagne"/>
<country id="76" nom="France"/>
andrewjames :

The following example will print <country id="98" nom="Espagne"/><country id="76" nom="France"/>:

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.InputSource;
import java.io.StringReader;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.ls.LSSerializer;

...

String xml = "<root><countries><country id=\"98\" nom=\"Espagne\"/><country id=\"76\" nom=\"France\"/></countries></root>";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xml));
Document doc = builder.parse(is);
Node node = doc.getElementsByTagName("countries").item(0);
String innerXml = getInnerXml(node);
System.out.println(innerXml);

And the helper method getInnerXml(node) looks like this:

private String getInnerXml(Node node) {
    DOMImplementationLS lsImpl = (DOMImplementationLS) node.getOwnerDocument().getImplementation().getFeature("LS", "3.0");
    LSSerializer lsSerializer = lsImpl.createLSSerializer();
    lsSerializer.getDomConfig().setParameter("xml-declaration", false);
    NodeList childNodes = node.getChildNodes();
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < childNodes.getLength(); i++) {
        sb.append(lsSerializer.writeToString(childNodes.item(i)));
    }
    return sb.toString();
}

Let me know if I have misunderstood the requirement (again!).

The warning here is that this is not a great solution. It involves constructing XML "by hand" (i.e. string concatenation) and that carries some risk that the results will be brittle or even broken, if the input is unexpectedly different or complex.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=194663&siteId=1