Module  java.xml.bind
软件包  javax.xml.bind

Interface Unmarshaller

  • 所有已知实现类:
    AbstractUnmarshallerImpl


    public interface Unmarshaller
    Unmarshaller类管理将XML数据反序列化为新创建的Java内容树的过程,可选地在未编组的情况下验证XML数据。 它为许多不同的输入类型提供了未装模式的超载。

    从文件解组:

           JAXBContext jc = JAXBContext.newInstance( "com.acme.foo" );
           Unmarshaller u = jc.createUnmarshaller();
           Object o = u.unmarshal( new File( "nosferatu.xml" ) );
        

    从InputStream解组:

           InputStream is = new FileInputStream( "nosferatu.xml" );
           JAXBContext jc = JAXBContext.newInstance( "com.acme.foo" );
           Unmarshaller u = jc.createUnmarshaller();
           Object o = u.unmarshal( is );
        

    从网址解组:

           JAXBContext jc = JAXBContext.newInstance( "com.acme.foo" );
           Unmarshaller u = jc.createUnmarshaller();
           URL url = new URL( "http://beaker.east/nosferatu.xml" );
           Object o = u.unmarshal( url );
        

    使用javax.xml.transform.stream.StreamSource从StringBuffer解组:

    
           JAXBContext jc = JAXBContext.newInstance( "com.acme.foo" );
           Unmarshaller u = jc.createUnmarshaller();
           StringBuffer xmlStr = new StringBuffer( "<?xml version="1.0"?>..." );
           Object o = u.unmarshal( new StreamSource( new StringReader( xmlStr.toString() ) ) );
        

    org.w3c.dom.Node解组:

           JAXBContext jc = JAXBContext.newInstance( "com.acme.foo" );
           Unmarshaller u = jc.createUnmarshaller();
    
           DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
           dbf.setNamespaceAware(true);
           DocumentBuilder db = dbf.newDocumentBuilder();
           Document doc = db.parse(new File( "nosferatu.xml"));
    
           Object o = u.unmarshal( doc );
        

    从使用客户端指定的验证SAX2.0解析器的javax.xml.transform.sax.SAXSource解组:

           // configure a validating SAX2.0 parser (Xerces2)
           static final String JAXP_SCHEMA_LANGUAGE =
               "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
           static final String JAXP_SCHEMA_LOCATION =
               "http://java.sun.com/xml/jaxp/properties/schemaSource";
           static final String W3C_XML_SCHEMA =
               "http://www.w3.org/2001/XMLSchema";
    
           System.setProperty( "javax.xml.parsers.SAXParserFactory",
                               "org.apache.xerces.jaxp.SAXParserFactoryImpl" );
    
           SAXParserFactory spf = SAXParserFactory.newInstance();
           spf.setNamespaceAware(true);
           spf.setValidating(true);
           SAXParser saxParser = spf.newSAXParser();
    
           try {
               saxParser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
               saxParser.setProperty(JAXP_SCHEMA_LOCATION, "http://....");
           } catch (SAXNotRecognizedException x) {
               // exception handling omitted
           }
    
           XMLReader xmlReader = saxParser.getXMLReader();
           SAXSource source =
               new SAXSource( xmlReader, new InputSource( "http://..." ) );
    
           // Setup JAXB to unmarshal
           JAXBContext jc = JAXBContext.newInstance( "com.acme.foo" );
           Unmarshaller u = jc.createUnmarshaller();
           ValidationEventCollector vec = new ValidationEventCollector();
           u.setEventHandler( vec );
    
           // turn off the JAXB provider's default validation mechanism to
           // avoid duplicate validation
           u.setValidating( false )
    
           // unmarshal
           Object o = u.unmarshal( source );
    
           // check for events
           if( vec.hasEvents() ) {
              // iterate over events
           }
        

    从StAX XMLStreamReader解集:

           JAXBContext jc = JAXBContext.newInstance( "com.acme.foo" );
           Unmarshaller u = jc.createUnmarshaller();
    
           javax.xml.stream.XMLStreamReader xmlStreamReader =
               javax.xml.stream.XMLInputFactory().newInstance().createXMLStreamReader( ... );
    
           Object o = u.unmarshal( xmlStreamReader );
        

    从StAX XMLEventReader解组:

           JAXBContext jc = JAXBContext.newInstance( "com.acme.foo" );
           Unmarshaller u = jc.createUnmarshaller();
    
           javax.xml.stream.XMLEventReader xmlEventReader =
               javax.xml.stream.XMLInputFactory().newInstance().createXMLEventReader( ... );
    
           Object o = u.unmarshal( xmlEventReader );
        

    解组XML数据

    Unmarshalling can deserialize XML data that represents either an entire XML document or a subtree of an XML document. Typically, it is sufficient to use the unmarshalling methods described by Unmarshal root element that is declared globally. These unmarshal methods utilize JAXBContext's mapping of global XML element declarations and type definitions to JAXB mapped classes to initiate the unmarshalling of the root element of XML data. When the JAXBContext's mappings are not sufficient to unmarshal the root element of XML data, the application can assist the unmarshalling process by using the unmarshal by declaredType methods. These methods are useful for unmarshalling XML data where the root element corresponds to a local element declaration in the schema.
    An unmarshal method never returns null. If the unmarshal process is unable to unmarshal the root of XML content to a JAXB mapped object, a fatal error is reported that terminates processing by throwing JAXBException.

    解组名为全局声明的根元素

    The unmarshal methods that do not have an declaredType parameter use JAXBContext to unmarshal the root element of an XML data. The JAXBContext instance is the one that was used to create this Unmarshaller. The JAXBContext instance maintains a mapping of globally declared XML element and type definition names to JAXB mapped classes. The unmarshal method checks if JAXBContext has a mapping from the root element's XML name and/or @xsi:type to a JAXB mapped class. If it does, it umarshalls the XML data using the appropriate JAXB mapped class. Note that when the root element name is unknown and the root element has an @xsi:type, the XML data is unmarshalled using that JAXB mapped class as the value of a JAXBElement. When the JAXBContext object does not have a mapping for the root element's name nor its @xsi:type, if it exists, then the unmarshal operation will abort immediately by throwing a UnmarshalException. This exception scenario can be worked around by using the unmarshal by declaredType methods described in the next subsection.

    通过声明类型 解密

    The unmarshal methods with a declaredType parameter enable an application to deserialize a root element of XML data, even when there is no mapping in JAXBContext of the root element's XML name. The unmarshaller unmarshals the root element using the application provided mapping specified as the declaredType parameter. Note that even when the root element's element name is mapped by JAXBContext, the declaredType parameter overrides that mapping for deserializing the root element when using these unmarshal methods. Additionally, when the root element of XML data has an xsi:type attribute and that attribute's value references a type definition that is mapped to a JAXB mapped class by JAXBContext, that the root element's xsi:type attribute takes precedence over the unmarshal methods declaredType parameter. These methods always return a JAXBElement<declaredType> instance. The table below shows how the properties of the returned JAXBElement instance are set.
    Unmarshal By Declared Type returned JAXBElement
    JAXBElement Property Value
    name xml element name
    value instanceof declaredType
    declaredType unmarshal method declaredType parameter
    scope null (actual scope is unknown)

    以下是unmarshal by declaredType method的示例。

    org.w3c.dom.Node由声明类型从一个org.w3c.dom.Node

    
           Schema fragment for example
           <xs:schema>
              <xs:complexType name="FooType">...<\xs:complexType>
              <!-- global element declaration "PurchaseOrder" -->
              <xs:element name="PurchaseOrder">
                  <xs:complexType>
                     <xs:sequence>
                        <!-- local element declaration "foo" -->
                        <xs:element name="foo" type="FooType"/>
                        ...
                     </xs:sequence>
                  </xs:complexType>
              </xs:element>
           </xs:schema>
    
           JAXBContext jc = JAXBContext.newInstance( "com.acme.foo" );
           Unmarshaller u = jc.createUnmarshaller();
    
           DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
           dbf.setNamespaceAware(true);
           DocumentBuilder db = dbf.newDocumentBuilder();
           Document doc = db.parse(new File( "nosferatu.xml"));
           Element  fooSubtree = ...; // traverse DOM till reach xml element foo, constrained by a
                                      // local element declaration in schema.
    
           // FooType is the JAXB mapping of the type of local element declaration foo.
           JAXBElement<FooType> foo = u.unmarshal( fooSubtree, FooType.class);
        

    支持符合SAX2.0标准的解析器

    A client application has the ability to select the SAX2.0 compliant parser of their choice. If a SAX parser is not selected, then the JAXB Provider's default parser will be used. Even though the JAXB Provider's default parser is not required to be SAX2.0 compliant, all providers are required to allow a client application to specify their own SAX2.0 parser. Some providers may require the client application to specify the SAX2.0 parser at schema compile time. See unmarshal(Source) for more detail.

    验证和成型

    A client application can enable or disable JAXP 1.3 validation mechanism via the setSchema(javax.xml.validation.Schema) API. Sophisticated clients can specify their own validating SAX 2.0 compliant parser and bypass the JAXP 1.3 validation mechanism using the unmarshal(Source) API.

    Since unmarshalling invalid XML content is defined in JAXB 2.0, the Unmarshaller default validation event handler was made more lenient than in JAXB 1.0. When schema-derived code generated by JAXB 1.0 binding compiler is registered with JAXBContext, the default unmarshal validation handler is DefaultValidationEventHandler and it terminates the marshal operation after encountering either a fatal error or an error. For a JAXB 2.0 client application, there is no explicitly defined default validation handler and the default event handling only terminates the unmarshal operation after encountering a fatal error.

    支持的属性

    There currently are not any properties required to be supported by all JAXB Providers on Unmarshaller. However, some providers may support their own set of provider specific properties.

    解散 事件回调

    The Unmarshaller provides two styles of callback mechanisms that allow application specific processing during key points in the unmarshalling process. In 'class defined' event callbacks, application specific code placed in JAXB mapped classes is triggered during unmarshalling. 'External listeners' allow for centralized processing of unmarshal events in one callback method rather than by type event callbacks.

    'Class defined' event callback methods allow any JAXB mapped class to specify its own specific callback methods by defining methods with the following method signature:

       // This method is called immediately after the object is created and before the unmarshalling of this
       // object begins. The callback provides an opportunity to initialize JavaBean properties prior to unmarshalling.
       void beforeUnmarshal(Unmarshaller, Object parent);
    
       //This method is called after all the properties (except IDREF) are unmarshalled for this object,
       //but before this object is set to the parent object.
       void afterUnmarshal(Unmarshaller, Object parent);
     
    The class defined callback methods should be used when the callback method requires access to non-public methods and/or fields of the class.

    The external listener callback mechanism enables the registration of a Unmarshaller.Listener instance with an setListener(Listener). The external listener receives all callback events, allowing for more centralized processing than per class defined callback methods. The external listener receives events when unmarshalling process is marshalling to a JAXB element or to JAXB mapped class.

    The 'class defined' and external listener event callback methods are independent of each other, both can be called for one event. The invocation ordering when both listener callback methods exist is defined in Unmarshaller.Listener.beforeUnmarshal(Object, Object) and Unmarshaller.Listener.afterUnmarshal(Object, Object).

    An event callback method throwing an exception terminates the current unmarshal process.

    从以下版本开始:
    1.6,JAXB 1.0
    另请参见:
    JAXBContextMarshallerValidator
    • 方法详细信息

      • unmarshal

        Object unmarshal​(Source source)
                  throws JAXBException
        从指定的XML Source中解组XML数据并返回生成的内容树。

        实现Unmarshal Global Root Element

        SAX 2.0解析器可插拔性

        客户端应用程序可以选择不使用JAXB提供程序提供的默认解析器机制。 任何SAX 2.0兼容解析器可以替代JAXB提供程序的默认机制。 为此,客户端应用程序必须正确配置包含由SAX 2.0解析器提供程序实现的SAXSourceXMLReader 如果XMLReader在其org.xml.sax.ErrorHandler注册了一个org.xml.sax.ErrorHandler ,它将被JAXB提供者替换,以便通过JAXB的ValidationEventHandler机制报告验证错误。 如果SAXSource不包含XMLReader ,则将使用JAXB提供程序的默认解析器机制。

        此解析器替换机制也可用于替换JAXB提供者的解组时间验证引擎。 客户端应用程序必须正确配置其SAX 2.0兼容解析器才能执行验证(如上面的示例所示)。 解析器在解组操作期间遇到的任何SAXParserExceptions将由JAXB提供商处理,并转换为JAXB ValidationEvent对象,这些对象将通过ValidationEventHandler注册的Unmarshaller向客户端报告。 注意:指定替代验证SAX 2.0解析器进行解组合并不一定取代JAXB提供程序用于执行按需验证的验证引擎。

        客户端应用程序指定在unmarshal(SAXSource)期间使用的替代解析器机制的唯一方法是通过unmarshal(SAXSource) API。 所有其他形式的解组方法(文件,URL,节点等)将使用JAXB提供程序的默认解析器和验证器机制。

        参数
        source - source XML数据的XML源(提供者只需要支持SAXSource,DOMSource和StreamSource)
        结果
        新创建的java内容树的根对象
        异常
        JAXBException - 如果在解组时出现意外的错误
        UnmarshalException - 如果ValidationEventHandler从其handleEvent方法返回false,或者Unmarshaller无法执行XML到Java绑定。 Unmarshalling XML Data
        IllegalArgumentException - 如果Source参数为空
        另请参见:
        unmarshal(javax.xml.transform.Source, Class)
      • getUnmarshallerHandler

        UnmarshallerHandler getUnmarshallerHandler​()
        获取可以用作XML管道中组件的解组员处理程序对象。

        JAXB提供程序可以返回相同的处理程序对象,用于此方法的多次调用。 换句话说,这种方法不一定会创建一个新的UnmarshallerHandler实例。 如果应用程序需要使用多个UnmarshallerHandler ,应该创建多个Unmarshaller

        结果
        unmarshaller处理程序对象
        另请参见:
        UnmarshallerHandler
      • setValidating

        void setValidating​(boolean validating)
                    throws JAXBException
        已过时。 由于JAXB2.0 ,请参阅setSchema(javax.xml.validation.Schema)
        指定Unmarshaller的默认验证机制是否在Unmarshaller操作期间进行验证。 默认情况下, Unmarshaller不进行验证。

        该方法只能在调用其中一个解组方法之前或之后调用。

        此方法仅控制JAXB提供程序的默认解组时间验证机制 - 它对指定自己的验证SAX 2.0兼容解析器的客户端没有影响。 指定自己的解密时间验证机制的客户端可能希望通过此API关闭JAXB提供商的默认验证机制,以避免“双重验证”。

        此方法自JAXB 2.0以来已弃用 - 请使用新的setSchema(javax.xml.validation.Schema) API。

        参数
        validating - 如果解 validating在解组织期间验证, validating true,否则为false
        异常
        JAXBException - 如果在 JAXBException时启用或禁用验证时发生错误
        UnsupportedOperationException - 如果在引用JAXB 2.0映射类的JAXBContext创建的Unmarshaller上调用此方法,则可能会抛出
      • isValidating

        boolean isValidating​()
                      throws JAXBException
        已过时。 由于JAXB2.0 ,请参阅getSchema()
        指示Unmarshaller是否配置为在解组操作期间进行验证。

        该API返回JAXB提供程序的默认unmarshal-time验证机制的状态。

        此方法自JAXB 2.0以来已弃用 - 请使用新的getSchema() API。

        结果
        如果Unmarshaller配置为在解组操作期间进行验证,则为true,否则为false
        异常
        JAXBException - 如果在检索验证标志时发生错误
        UnsupportedOperationException - 如果在引用JAXB 2.0映射类的JAXBContext创建的Unmarshaller上调用此方法,则可能会抛出
      • setEventHandler

        void setEventHandler​(ValidationEventHandler handler)
                      throws JAXBException
        允许申请注册一个ValidationEventHandler

        如果在调用任何解组方法时遇到任何验证错误,则JAXB提供程序将调用ValidationEventHandler 如果客户端应用程序在调用ValidationEventHandler方法之前未注册ValidationEventHandler ,则ValidationEvents将由默认事件处理程序处理,该事件处理程序将在遇到第一个错误或致命错误后终止解组操作。

        使用null参数调用此方法将导致Unmarshaller恢复为默认事件处理程序。

        参数
        handler - 验证事件处理程序
        异常
        JAXBException - 如果在设置事件处理程序时遇到错误
      • getEventHandler

        ValidationEventHandler getEventHandler​()
                                        throws JAXBException
        返回当前事件处理程序或默认事件处理程序(如果尚未设置)。
        结果
        当前的ValidationEventHandler或默认事件处理程序(如果尚未设置)
        异常
        JAXBException - 如果在获取当前事件处理程序时遇到错误
      • setProperty

        void setProperty​(String name,
                         Object value)
                  throws PropertyException
        在底层实现中设置特定属性Unmarshaller 此方法只能用于设置上述标准JAXB定义属性之一或提供者特定属性。 尝试设置未定义的属性将导致抛出PropertyException。 Supported Properties
        参数
        name - 要设置的属性的名称。 可以使用常数字段或用户提供的字符串指定此值。
        value - 要设置的属性的值
        异常
        PropertyException - 处理给定属性或值时出错
        IllegalArgumentException - 如果name参数为空
      • getProperty

        Object getProperty​(String name)
                    throws PropertyException
        获取底层实现中的特定属性Unmarshaller 此方法只能用于获取上述标准JAXB定义的属性之一或提供者特定属性。 尝试获取未定义的属性将导致抛出PropertyException。 Supported Properties
        参数
        name - 要检索的属性的名称
        结果
        请求的属性的值
        异常
        PropertyException - 检索给定属性或值属性名称时出错
        IllegalArgumentException - 如果name参数为空
      • setSchema

        void setSchema​(Schema schema)
        指定应用于验证后续解组操作的JAXP 1.3 Schema对象。 将null传递给此方法将禁用验证。

        这种方法代替了已过时setValidating(boolean) API。

        最初此属性设置为null

        参数
        schema - 验证解组操作的模式对象或禁用验证的null
        异常
        UnsupportedOperationException - 如果在引用JAXB 1.0映射类的JAXBContext创建的Unmarshaller上调用此方法,则可能会抛出
        从以下版本开始:
        1.6,JAXB 2.0
      • getSchema

        Schema getSchema​()
        获取用于执行解密时间验证的JAXP 1.3 Schema对象。 如果在unmarshaller上没有设置Schema,则该方法将返回null,表示将不执行解密时间验证。

        此方法为不支持的 API提供了替代功能以及对Schema对象的访问。 要确定Unmarshaller是否启用了验证,只需将null的返回类型测试:

           boolean isValidating = u.getSchema()!=null;  
        结果
        用于执行解密时间验证的Schema对象,如果不存在则使用null
        异常
        UnsupportedOperationException - 如果在引用JAXB 1.0映射类的JAXBContext创建的Unmarshaller上调用此方法,则可能会抛出
        从以下版本开始:
        1.6,JAXB 2.0
      • setAttachmentUnmarshaller

        void setAttachmentUnmarshaller​(AttachmentUnmarshaller au)

        将解析cid,content-id URI的上下文关联到作为附件传递的二进制数据。

        即使在解组器执行XOP处理时,也必须支持通过setSchema(Schema)启用解密时间验证。

        异常
        IllegalStateException - 如果在解组操作期间尝试同时调用此方法。
      • setListener

        void setListener​(Unmarshaller.Listener listener)

        注册unmarshal事件回调Unmarshaller.Listener与这Unmarshaller

        每个Unmarshaller只有一个监听器。 设置侦听器将替换以前设置的侦听器。 可以通过将侦听器设置为null来取消注册当前侦听器。

        参数
        listener - 为此Unmarshaller提供了解组件事件回调
        从以下版本开始:
        1.6,JAXB 2.0