JAXB XSD名称空间unmarshal返回null

时间:2015-11-23 09:01:01

标签: java xml xsd jaxb

我想将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)

1 个答案:

答案 0 :(得分:1)

我遇到了同样的问题。我通过这个answer解决了这个问题。

解决方案是使用包上的@XmlSchema注释创建package-info.java文件。

<强> package-info.java

XmlSchema( 
    namespace = "http://www.ba.com/schema/BAserviceDeskAPI/incident", 
    elementFormDefault = XmlNsForm.QUALIFIED) 
package example;

import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;