且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JAXB:如何在没有命名空间的情况下解组XML

更新时间:2022-06-19 21:16:20

更简单的方法可能是使用 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