基于Java的XML节点提取
嗨,我需要提取XML字符串中的customer name元素部分。我如何用Java实现它。我的目的是将xml解组到java对象 下面的代码是我的响应字符串。有人能帮我从这个xml中提取customer元素吗基于Java的XML节点提取,java,xml,unmarshalling,Java,Xml,Unmarshalling,嗨,我需要提取XML字符串中的customer name元素部分。我如何用Java实现它。我的目的是将xml解组到java对象 下面的代码是我的响应字符串。有人能帮我从这个xml中提取customer元素吗 <?xml version="1.0" encoding="UTF-8"?> <response> <control> <status>success</status> <senderid&
<?xml version="1.0" encoding="UTF-8"?>
<response>
<control>
<status>success</status>
<senderid>XXXX</senderid>
<controlid>ControlIdHere</controlid>
<uniqueid>false</uniqueid>
<dtdversion>3.0</dtdversion>
</control>
<operation>
<authentication>
<status>XXXX</status>
<userid>XXXX</userid>
<companyid>XXXXXX</companyid>
<sessiontimestamp>2014-08-12T03:49:00-07:00</sessiontimestamp>
</authentication>
<result>
<status>success</status>
<function>readByQuery</function>
<controlid>testControlId</controlid>
<data listtype="customer" count="26" totalcount="26" numremaining="0">
<customer>
<RECORDNO>15</RECORDNO>
<CUSTOMERID>RIC001</CUSTOMERID>
<NAME>XYZ</NAME>
<ENTITY>CRIC001</ENTITY>
<PARENTKEY></PARENTKEY>
<PARENTID></PARENTID>
<PARENTNAME></PARENTNAME>
</customer>
<customer>
<RECORDNO>15</RECORDNO>
<CUSTOMERID>RIC001</CUSTOMERID>
<NAME>BBB</NAME>
<ENTITY>CRIC001</ENTITY>
<PARENTKEY></PARENTKEY>
<PARENTID></PARENTID>
<PARENTNAME></PARENTNAME>
</customer>
</data>
</result>
</operation>
</response>
我已经在原始帖子中更新了我的解组代码。你可能会得到一个ClassCastException,为什么不在你的问题中包含它呢?当字符串被解组时,它是根节点的类型。这是回应,而不是客户。您需要浏览对象树。我需要浏览对象树并仅提取客户对象。我需要写一些代码来得到它。我正在寻找有关编写代码的帮助您可以尝试通过XPath:node node=NodeExpath.EvaluatePathExpression、document、XPathConstants.node检索customer节点,其中xpathExpression可能类似于//customer。然后,您可以通过方法将节点转换为文档,或者对节点执行任何操作。请注意,您不仅限于StaX,还可以使用或
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
javax.xml.bind.Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Customer customer = (Customer) jaxbUnmarshaller.unmarshal(new StreamSource(new StringReader(response.toString() ) ) );
System.out.println(customer.getNAME());