Java – 将xml对象转换为String

所以我使用xPath从xml文档中提取特定的标签和元素并将其存储在对象中.我的问题是如何将此对象转换为字符串.我尝试过.toString()方法,但它给我的全部内容如下:

LocalHost测试:org.apache.xml.dtm.ref.DTMNodeList@717e717e

我的代码如下:

DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
            domFactory.setNamespaceAware(true); // never forget this!
            DocumentBuilder builder = domFactory.newDocumentBuilder();
            org.w3c.dom.Document doc =  builder.parse("src/webSphere/testcases/positiveCode-data.xml");

            XPathFactory factory = XPathFactory.newInstance();
            XPath xpath = factory.newXPath();
            XPathExpression expr 
             = xpath.compile(" /tests/class/method/params[@name='config']/param/text()");
            MQQueueConnectionFactory cf = new MQQueueConnectionFactory();
            Object result = expr.evaluate(doc, XPathConstants.NODESET);


            System.out.println("LocalHost test: " + result.toString());

这是我的xml文件:

<?xml version ="1.0" encoding = "UTF-8"?>
<tests xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="http://jtestcase.sourceforge.net/dtd/jtestcase2.xsd">
    <class name="Success">
        <method name="success">
            <test-case name="positive-code">
                <params name="config">
                    <param name="hostName" type="java.lang.String">localhost</param>
                    <param name="port" type="int">7080</param>
                    <param name="transportType" type="java.lang.String">10</param>
                    <param name="queueManager" type="java.lang.String">MB8QMGR</param>
                    <param name="channel" type="java.lang.String">10</param>
                    <param name="inputQueue" type="java.lang.String">10</param>
                    <param name="outputQueue" type="java.lang.String">20</param>
                    <param name="testFile" type="java.lang.String">+</param>
                    <param name="expectedResultFile" type="java.lang.String">+</param>
                </params>
                <asserts>
                    <assert name="result" type="int" action="EQUALS">
                        30
                </assert>
                </asserts>
            </test-case>


        </method>
    </class>
</tests>
最佳答案
当然.您可以看到您有一个NodeList的实例.

您可以获取列表的长度,然后获取特定索引处的所有Node项目,并根据您对它们的期望打印出来 – 很可能是它们的文本内容,所以Node#getTextContent()(或者您想要打印的任何其他项目 – 节点名称,节点类型等)循环中.

NodeList resultList = (NodeList)expr.evaluate(doc, XPathConstants.NODESET);
int listLength = resultList.getLength();
for (int i = 0; i < listLength; i++) {
    System.out.println("LocalHost test (" + i + "): " + resultList.item(i).getTextContent());
}

编辑

如果您期望单个String值,那么就可以

String resultList = (String)expr.evaluate(doc, XPathConstants.STRING);

这会将结果转换为XPath String conversion rules之后的字符串.

转载注明原文:Java – 将xml对象转换为String - 代码日志