在 Java 中将 NodeList 转换为字符串

Converting NodeList to String in Java

我正在尝试将 NodeList 转换为 String,以便我可以以任何我想要的方式操作它,但我似乎无法在网上找到答案。

我试过将 NodeList 存储在 Node 数组中,但打印出的所有数据都是空的。

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();
        }

    }

}

}

用于打印 Preference1 个元素

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

这个 Convert Node to String 它按原样获取 XML 节点,如果您只需要没有 XML 的内容,请使用 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

您可以打印节点名称如下

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