【发布时间】:2016-01-11 17:29:07
【问题描述】:
我想将一个 xml 文件映射到 Java 对象中。我有一个模式来验证 xml。
Java 类
Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(
new File("src/PersonDetails.xsd"));
jaxbContext = JAXBContext.newInstance(Person.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
unmarshaller.setSchema(schema);
Person response = (Person ) unmarshaller.unmarshal(newFileInputStream("src/PersonDetails.xml"));
System.out.println(response.getPersonNo());
PersonDetails.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://www.example.com"
targetNamespace="http://www.example.com" elementFormDefault="qualified"
version="1-0-20101115" id="PersonDetails">
<xs:element name="PersonDetails">
<xs:complexType>
<xs:sequence>
<xs:element name="PersonNo" nillable="false">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:maxLength value="30" />
</xs:restriction>
</xs:simpleType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
PersonDetails.xml
<?xml version="1.0" encoding="UTF-8"?>
<PersonDetails xmlns="http://www.example.com"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.example.com PersonDetails_v1-0-20101115.xsd">
<PersonNo>PERS-0001-000001</PersonNo>
</PersonDetails>
Person.class
@XmlRootElement(name = "PersonDetails", namespace="http://www.example.com")
public class Person {
private String personNo;
@XmlElement(name = "PersonNo")
public String getPersonNo(){
return personNo;
}
}
personNo 返回 null。如果我从 xsd 和 xml 中删除了命名空间和 xmlns 声明,我可以获得正确的值。
当我尝试使用相同的架构进行 Marshall 时,我收到了这个错误:
javax.xml.bind.MarshalException
- with linked exception:
[org.xml.sax.SAXParseException; lineNumber: 0; columnNumber: 0; cvc-complex-type.2.4.a: Invalid content was found starting with element 'PersonNo'. One of '{"http://www.example.com":PersonNo}' is expected.]
at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.write(Unknown Source)
at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.marshal(Unknown Source)
at javax.xml.bind.helpers.AbstractMarshallerImpl.marshal(Unknown Source)
at Test.main(Test.java:35)
【问题讨论】:
-
newFileInputStream("src/PersonDetails.xml") 这个流不为空吧?
-
你确认不为空,如果我删除命名空间,xmlns 所有这些声明我都能够获取数据。我尝试使用 StringReader 也一样