在Java中将NodeList转换为String

时间:2015-07-14 07:00:24

标签: java xpath tostring nodelist

我试图将NodeList转换为String,这样我就可以按照我想要的方式操作它,但我似乎无法在线找到答案。

我尝试将NodeList存储在Node数组中,但打印出来的所有数据都是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();
        }

    }

}

}

3 个答案:

答案 0 :(得分:9)

如果只需要使用不使用XML的内容getTextContent

,则将节点转换为字符串,它将节点作为XML获取
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

答案 1 :(得分:0)

用于打印Preference1元素

使用System.out.println(nod.getTextContent());

答案 2 :(得分:0)

您可以按如下方式打印节点名称

System.out.println(node.getNodeName());