在Java中将NodeList转换为字符串

3

我正在尝试将NodeList转换为字符串,以便可以按照自己的意愿进行操作,但是我似乎找不到在线答案。

我尝试将NodeList存储在节点数组中,但是打印出来的所有数据都将为空。

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

    }

}

}


尝试使用 System.out.println(nod.getTextContent()); - Raghavendra
你的代码没有显示出任何实际尝试转换为字符串。你想要转换什么?那些“…”里面是什么?为什么你认为String将允许你比DOM更好地操作? - RealSkeptic
@RealSkeptic “…”是我尝试自己解决问题的地方,但由于没有成功,我删除了整个代码块。我希望在另一个类中使用NodeList的存储值。 - Ashton
3个回答

13

将节点转换为字符串,以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

0

用于打印Preference1元素

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


这只打印“实际文本内容”,即<b>c</b>中的“c”,但不包括任何内部节点,遗憾地... - rogerdpack

-1

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接