[英]Unmarshalling String XML with JAXB not working and returning just null values
我试图将一个字符串 XML 解组为一个 POJO 对象,但没有成功。 这是我正在使用的代码
MyObject myobject = JAXB.unmarshal(new StringReader(myxmlstring), MyObject.class);
Xml 的结构和对象的结构如下:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:SomePerson xmlns:ns2="http://to/something">
<SomePerson>
<person>
<name>joe</name>
</person>
</SomePerson>
</ns2:SomePerson>
这是我的对象:
@XmlRootElement(name="SomePerson")
@XmlAccessorType(XmlAccessType.FIELD)
public class MyObject {
@XmlElement(name = "name")
private String name;
//getter and setters
}
建议你做这样的事情::
final DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final InputSource is = new InputSource();
is.setCharacterStream(new StringReader("<root><node1></node1></root>")); // put your xml string here
final Document doc = db.parse(is);
final XMLInputFactory xif = XMLInputFactory.newFactory();
final DOMSource domSource = new DOMSource(document);
final XMLStreamReader xsr = xif.createXMLStreamReader(domSource);
final XMLReaderWithoutNamespace xr = new XMLReaderWithoutNamespace(xsr);
final Unmarshaller unmarshaller = JAXBContext
.newInstance("POJO LOCATION").createUnmarshaller();
return (POJOClass) unmarshaller.unmarshal(xr);
让我知道这是否有帮助
您的类 MyObject 使用名为“SomePerson”的根元素描述 XML 结构,其中包含子元素“name”,如下所示:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<SomePerson>
<name>joe</name>
</SomePerson>
您尝试解析的 XML 包含其他元素“SomePerson”和“person”,这些元素未在您的 JAXB 类中描述:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:SomePerson xmlns:ns2="http://to/something">
<SomePerson> <!-- definition missing -->
<person> <!-- definition missing -->
<name>joe</name>
</person>
</SomePerson>
</ns2:SomePerson>
您应该修复 XML 文档的结构或将缺失的字段添加到 JAXB 类定义中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.