如何在没有名称空间的情况下解组

如何在没有名称空间的情况下解组

本文介绍了JAXB:如何在没有名称空间的情况下解组 XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 XML 文件:

I have an XML file:

<?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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 07:53