我正在尝试解组给定的 XML:
<FHcomment>
<TX>rewriting of file</TX>
<tool_id>toolA</tool_id>
<tool_vendor>Company</tool_vendor>
<tool_version>1.7.36.0</tool_version>
</FHcomment>
该模式已编译为 JAXB 类,请参见此处:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"tx",
"toolId",
"toolVendor",
"toolVersion",
"userName",
"commonProperties",
"extensions"
})
@XmlRootElement(name = "FHcomment")
public class FHcomment {
@XmlElement(name = "TX", required = true)
protected TX tx;
@XmlElement(name = "tool_id", required = true)
protected BaseName toolId;
@XmlElement(name = "tool_vendor", required = true)
protected BaseName toolVendor;
@XmlElement(name = "tool_version", required = true)
protected BaseVersion toolVersion;
@XmlElement(name = "user_name")
protected BaseName userName;
@XmlElement(name = "common_properties")
protected CommonPropertiesType commonProperties;
protected ExtensionsType extensions;
@XmlAnyAttribute
private Map<QName, String> otherAttributes = new HashMap<QName, String>();
.....
/*
* GETTERS and SETTERS for the fields have been removed here
*/
.....
}
我解组 XML 的代码如下:
JAXBContext jc = JAXBContext.newInstance(FHcomment.class);
String s = "<FHcomment>....</Fhcomment>";
Unmarshaller unmarshaller = jc.createUnmarshaller();
XMLInputFactory fac = XMLInputFactory.newFactory();
XMLStreamReader xsr = fac.createXMLStreamReader(new StringReader(s));
JAXBElement<FHcomment> foo = unmarshaller.unmarshal(xsr, FHcomment.class);
FHcomment val = foo.getValue();
问题:生成的 FHcomment 对象不包含 FHcomment 的子元素。全部为空,这不是所需的结果。
如何告诉 JAXB 将给定的 XML 完全解组为对象?
编辑:将 ValidationHandler 添加到 Unmsarshaller 后,我更接近问题:
意外元素(uri:“”,本地:“TX”)。预期的元素是 <{htp://www.example.com/mdf/v4}tool_id>、<{htp://www.example.com/mdf/v4}TX>、<{htp://www.www .example.com/mdf/v4}common_properties>,<{htp://www.example.com/mdf/v4}tool_version>,<{htp://www.example.com/mdf/v4}extensions>, <{htp://www.www.example.com/mdf/v4}tool_vendor>,<{htp://www.www.example.com/mdf/v4}user_name>
意外元素(uri:“”,本地:“tool_id”)。预期的元素是......
事实证明,JAXB 不喜欢提供的 XML 不包含命名空间信息的事实。那么我如何告诉解组器忽略命名空间?
编辑2:
经过更多研究后,我找不到一种方法来欺骗 JAXB 在没有命名空间验证的情况下工作。我使用http://cooljavablogs.blogspot.de/2008/08/how-to-instruct-jaxb-to-ignore.html上的教程来规避我的问题。不是一个很好的解决方案,但最好的解决方案......