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"/>
6
  • 1
    See this question: How can I read Xml attributes using Java? Commented Mar 10, 2020 at 17:07
  • @andrewjames, sorry its not the same as i want Commented Mar 10, 2020 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 in Java DOM. I hope that actually does help! There are a few options - some are not recommended, though. Commented Mar 10, 2020 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 Commented Mar 10, 2020 at 19:53
  • I have updated my example. It produces what I think you need. Take a look! Commented Mar 10, 2020 at 20:18

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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 : <country id="98" nom="Espagne"/> <country id="76" nom="France"/>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.