簡體   English   中英

JAXB編組和解組

[英]JAXB marshaller & unmarsharller

我使用JAXB編組器將對象編組到System.out,如下所示:

JAXBContext ctxt = JAXBContext.newInstance(CONTEXT);
Marshaller m = ctxt.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
m.marshal(map, System.out);

然后將輸出另存為x.xml文件:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:sourceCategoryMap xmlns:ns2="http://schemas.xyz.com/services/1.0">
    <ns2:source-category-map>
        <entry>
            <key>Seattle</key>
            <map>
                <entry>
                    <key>Restaurant</key>
                    <value>Restaurant</value>
                </entry>
                <entry>
                    <key>Fun</key>
                    <value>Entertainment</value>
                </entry>
            </map>
        </entry>
        <entry>
            <key>Honolulu</key>
            <map>
                <entry>
                    <key>Food</key>
                    <value>Restaurant</value>
                </entry>
            </map>
        </entry>
    </ns2:source-category-map>
</ns2:sourceCategoryMap>

接下來,我從x.xml生成架構文件為x.xsd:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" xmlns:ns2="http://schemas.xyz.com/services/1.0">
  <xs:import namespace="http://schemas.xyz.com/services/1.0" schemaLocation="ns2.xsd"/>
  <xs:element name="entry">
    <xs:complexType>
      <xs:sequence minOccurs="0">
        <xs:choice maxOccurs="unbounded">
          <xs:element ref="key"/>
          <xs:element ref="map"/>
        </xs:choice>
        <xs:element ref="value"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:element name="key" type="xs:string"/>
  <xs:element name="map">
    <xs:complexType>
      <xs:sequence>
        <xs:element maxOccurs="unbounded" ref="entry"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:element name="value" type="xs:NCName"/>
</xs:schema>

最后,我嘗試對x.xsd進行解組和驗證x.xml文件,如下所示:

Unmarshaller um =  MarshalUtils.getUnmarshaller();            
        SchemaFactory sf = SchemaFactory.newInstance(
                javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = sf.newSchema(new File(SOURCE_REGION_SCHEMA));
        um.setSchema(schema);

        SourceRegionMap srm = (SourceRegionMap) um.unmarshal(input);

但它抱怨:

javax.xml.bind.UnmarshalException
 - with linked exception:
[org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'ns2:sourceCategoryMap'.]
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.createUnmarshalException(AbstractUnmarshallerImpl.java:315)

有人知道這是怎么回事嗎? 非常感謝!

不要從XML生成XSD。 要求JAXB使用schemagen命令從Java代碼生成它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM