JAXB:如何在没有命名空间的情况下解组XML [英] JAXB: How can I unmarshal XML without namespaces
问题描述
我有一个XML文件:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<object>
<str>the type</str>
<bool type="boolean">true</bool>
</object>
我想把它解组为下面一个类的对象
And I want to unmarshal it to an object of the class below
@XmlRootElement(name="object")
public class Spec {
public String str;
public Object bool;
}
我该怎么做?除非我指定名称空间(见下文),否则它不起作用。
How can I do this? Unless I specify namespaces (see below), it doesn't work.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<object>
<str>the type</str>
<bool xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xsi:type="xs:boolean">true</bool>
</object>
推荐答案
更简单的方法可能是使用 unmarshalByDeclaredType ,因为您已经知道了类型希望解组。
An easier way might be to use unmarshalByDeclaredType, since you already know the type you want to unmarshal.
使用
Unmarshaller.unmarshal(rootNode, MyType.class);
您不需要在XML中使用命名空间声明,因为您传入的JAXBElement是已设置名称空间。
you don't need to have a namespace declaration in the XML, since you pass in the JAXBElement that has the namespace already set.
这也是完全合法的,因为您不需要在XML实例中引用命名空间,请参阅 http://www.w3.org/TR/xmlschema-0/#PO - 许多客户以这种方式生成XML。
This also perfectly legal, since you are not required to reference a namespace in an XML instance, see http://www.w3.org/TR/xmlschema-0/#PO - and many clients produce XML in that fashion.
最后让它发挥作用。请注意,您必须删除架构中的任何自定义命名空间;这是工作示例代码:
Finally got it to work. Note that you have to remove any custom namespace in the schema; here's working sample code:
架构:
<xsd:schema
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="customer">
<xsd:complexType>
<xsd:sequence minOccurs="1" maxOccurs="1">
<xsd:element name="name" type="xsd:string" minOccurs="1" maxOccurs="1" />
<xsd:element name="phone" type="xsd:string" minOccurs="1" maxOccurs="1" />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
XML:
<?xml version="1.0" encoding="UTF-8"?>
<customer>
<name>Jane Doe</name>
<phone>08154712</phone>
</customer>
JAXB代码:
JAXBContext jc = JAXBContext.newInstance(Customer.class);
Unmarshaller u = jc.createUnmarshaller();
u.setSchema(schemaInputStream); // load your schema from File or any streamsource
Customer = u.unmarshal(new StreamSource(inputStream), clazz); // pass in your XML as inputStream
这篇关于JAXB:如何在没有命名空间的情况下解组XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!