0

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"/>
YSA
  • 35
  • 6
  • 1
    See this question: [How can I read Xml attributes using Java?](https://stackoverflow.com/questions/11560173/how-can-i-read-xml-attributes-using-java) – andrewJames Mar 10 '20 at 17:07
  • @andrewjames, sorry its not the same as i want – YSA Mar 10 '20 at 17:28
  • Ah, sorry - now I understand - you want the entire inner XML as a string. That is discussed in this question: [Get a node's inner XML as String](https://stackoverflow.com/questions/3300839/get-a-nodes-inner-xml-as-string-in-java-dom) in Java DOM. I hope that actually does help! There are a few options - some are not recommended, though. – andrewJames Mar 10 '20 at 19:18
  • I have already seen this example, the output is the same as what i written above.the problem is the string returned has the tag parent countries and i need only get the inner XML inside it – YSA Mar 10 '20 at 19:53
  • I have updated my example. It produces what I *think* you need. Take a look! – andrewJames Mar 10 '20 at 20:18
  • It's exactly what i need, Thank you a lot @andrewjames – YSA Mar 10 '20 at 21:24

1 Answers1

2

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.

andrewJames
  • 19,570
  • 8
  • 19
  • 51
  • Thx for your responde, but i dont need the values of the attributes. What i need its all inner html of countrie tag like this : – YSA Mar 10 '20 at 18:29