作者热门文章
- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
我有一个 XML 文件:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<object>
<str>the type</str>
<bool type="boolean">true</bool>
</object>
我想将它解码为下面类的一个对象
@XmlRootElement(name="object")
public class Spec {
public String str;
public Object bool;
}
我该怎么做?除非我指定命名空间(见下文),否则它不起作用。
<?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 ,因为您已经知道要解码的类型。
通过使用
Unmarshaller.unmarshal(rootNode, MyType.class);
您不需要在 XML 中声明 namespace ,因为您传入的 JAXBElement 已经设置了 namespace 。
这也是完全合法的,因为您不需要在 XML 实例中引用 namespace ,参见 http://www.w3.org/TR/xmlschema-0/#PO - 许多客户以这种方式生成 XML。
终于搞定了。请注意,您必须删除模式中的任何自定义 namespace ;这是工作示例代码:
架构:
<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
关于xml - JAXB:如何在没有 namespace 的情况下解码 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7184526/
我是一名优秀的程序员,十分优秀!