Converting NodeList to String in Java

Ashton picture Ashton · Jul 14, 2015 · Viewed 18.3k times · Source

I'm trying to convert NodeList to String so I can manipulate it in whichever way I want, but I can't seem to find an answer online.

I've tried storing the NodeList in a Node array, but all the data printed out would be null.

TextingXPath.java

import java.io.IOException;

public class TestingXPath {


static Node[] copy;
static int length;

public static void main(String[] args) throws SAXException, IOException,
        ParserConfigurationException {

    URL obj = new URL("http://jbossews-ashton.rhcloud.com/testXML.jsp");
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("GET");
    int responseCode = con.getResponseCode();

    if (responseCode == 200) {

        DocumentBuilderFactory domFactory = DocumentBuilderFactory
                .newInstance();
        try {
            DocumentBuilder builder = domFactory.newDocumentBuilder();
            Document dDoc = builder.parse(con.getInputStream());

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

            Node node = (Node) xPath.evaluate(
                    "/HDB/Resident[@Name='Batman ']/Preference", dDoc,
                    XPathConstants.NODE);
            if (null != node) {
                NodeList nodeList = node.getChildNodes();
                for (int i = 0; null != nodeList
                        && i < nodeList.getLength(); i++) {
                    Node nod = nodeList.item(i);
                    if (nod.getNodeType() == Node.ELEMENT_NODE)
                        {

                        ...

                        }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

}

Answer

Ali Helmy picture Ali Helmy · Jul 14, 2015

This Convert Node to String it gets the node as XML as is, if you need only the content with no XML use getTextContent

Node elem = nodeList.item(i);//Your Node
StringWriter buf = new StringWriter();
Transformer xform = TransformerFactory.newInstance().newTransformer();
xform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); // optional
xform.setOutputProperty(OutputKeys.INDENT, "yes"); // optional
xform.transform(new DOMSource(elem), new StreamResult(buf));
System.out.println(buf.toString()); // your string