Java Nerd
Java Nerd

Reputation: 968

Parse an XML and store results in a String

I am really new to XML Parsing in Java I have successfully read my XML using Java. Now The Problem is that I want to Populate a String with my the Parsing Results. My Code:

 DocumentBuilderFactory builderFactory =
    DocumentBuilderFactory.newInstance();
 DocumentBuilder builder = null;
try {

builder = builderFactory.newDocumentBuilder();
        org.w3c.dom.Document document = builder.parse(
        new FileInputStream("c:\\y.xml"));

        XPath xPath =  XPathFactory.newInstance().newXPath();

       String expression = "/ADOXML/MODELS/MODEL/INSTANCE/ATTRIBUTE[@name='Description' and @type='STRING']";

NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(document, XPathConstants.NODESET);
 int i;
for (i = 0; i < nodeList.getLength(); i++) {


 String txt=nodeList.item(i).getFirstChild().toString();
  System.out.print(txt);
}

System.out.print("\n\n\nIIIII="+i);

} catch (ParserConfigurationException | SAXException | IOException e) {
System.out.print(e);
}       

The Error it gives me:

NodeList can not convert to Java.Lang.String!

So how can i get rid of it can somebody help me please!

Upvotes: 1

Views: 122

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167436

I think you want String txt=nodeList.item(i).getTextContent(); instead of String txt=nodeList.item(i).getFirstChild().toString();.

Upvotes: 2

Related Questions