我想将一个元素解码到一个类属性中,其类型是对象,以保持它的通用性。
我尝试将类构建并编码为 xml,然后将其解码回来,结果很好。 但是当我尝试使用正常生成的 Xml 文档(尽管它具有相同的结构)执行此操作时,结果类对象属性的值为 null。
这是我的测试结构:
@XmlRootElement
public class TestStructure {
private Object test;
public Object getTest() {
return test;
}
public void setTest(Object test) {
this.test = test;
}
}
我尝试对其进行编码,并获取此 xml 文档:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<testStructure>
<test xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string">foo</test>
</testStructure>
但是,如果我尝试通过 Domsource 任意构建此结构以获得相同的 Xml 文档:
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// root element
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("testStructure");
doc.appendChild(rootElement);
Element test = doc.createElement("test");
test.appendChild(doc.createTextNode("foo"));
test.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
test.setAttribute("xsi:type", "xs:string");
test.setAttribute("xmlns:xs", "http://www.w3.org/2001/XMLSchema");
rootElement.appendChild(test);
并解码文档:
JAXBContext context2 = JAXBContext.newInstance(TestStructure.class);
Unmarshaller m2 = context2.createUnmarshaller();
TestStructure testobject2 =
( TestStructure ) m2.unmarshal(doc);
System.out.println(testobject2.getTest());
<小时/>
该属性似乎为“null”。
那么,到底出了什么问题?
最佳答案
哇哦,感谢W A ,我得到了解决方案:)
您只需修改元素属性:
Element test = doc.createElement("test");
test.appendChild(doc.createTextNode("foo"));
test.setAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "xsi:type", "xs:string");
test.setAttribute("xmlns:xs", "http://www.w3.org/2001/XMLSchema");
关于java - 如何将 xml 文档元素解码到对象属性中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18615378/