Java - convert xml object to String

So, I pull certain tags and elements from the XML document using xPath and save it in the object. My question is how can I convert this object to a string. I tried the .toString () method, but all it gave me is this:

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

my code is below:

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

here is my xml file:

 <?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> 
+4
source share
1 answer

Sure. You can see that you have an instance of NodeList .

You can get the length of the list and then all the Node elements in specific indexes and print them based on what you expect from them - most likely their textual content, so Node#getTextContent() (or whatever else you want print - node name, node type, etc.) in a loop.

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

EDIT

If you expect one String value to just do

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

This converts the result to the string following the XPath String Conversion Rules .

+2
source

Source: https://habr.com/ru/post/1493138/


All Articles