使用Java解组XML字符串
您好,我正在使用java为XML响应字符串编写一个解组脚本。我提到了xml响应、解组代码和我收到的错误。 请帮助解决问题,并就问题向我提供建议使用Java解组XML字符串,java,xml,unmarshalling,Java,Xml,Unmarshalling,您好,我正在使用java为XML响应字符串编写一个解组脚本。我提到了xml响应、解组代码和我收到的错误。 请帮助解决问题,并就问题向我提供建议 JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class); javax.xml.bind.Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); Customer customer = (Customer)
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());
Exception in thread "main" javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"response"). Expected elements are <{}customer>
<?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>
XML字符串不是有效的XML结束标记,但我假设在发布问题时这是一个错误 在解组到客户对象时,JAXB似乎不需要根元素。Customer类看起来像什么 Java类必须与 @XMLRootElement
类响应问题在于,您正在告诉解组器您想要一个Customer对象,并将给出一个表示Customer的XML字符串,但您正在传递一个表示Response对象的XML字符串。如果您有响应类,请使用它创建JAXBContext实例。如果不是,则获取响应中表示Customer对象的字符串
<customer>
<name>ABC</name>
<country>India<country>
</customer>
您当前正在尝试将用标记打开的XML转换为Customer对象 您需要专门为JAXBUnmarshaller提供元素,以使其工作。例如:
<customer>
<name>ABC</name>
<country>India<country>
</customer>
请参见这个问题:如何遍历XML直到到达customer元素。从那里可以解组XML:
谢谢分享。我是编程新手。我想这会管用的。我会尽力回复你的。哪一部分?你们有反应课吗?普里耶什。谢谢你的解决方案,我明白了。Priyesh我有数据和客户类。我在论坛上读到,通过设置XML根名称注释可以避免循环。你能调查一下这件事并向我提出建议吗
<customer>
<name>ABC</name>
<country>India<country>
</customer>