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

Interface Marshaller

  • 所有已知实现类:
    AbstractMarshallerImpl


    public interface Marshaller

    Marshaller类负责管理将Java内容树序列化为XML数据的过程。 它提供了基本的编组方法:

    假设以下所有代码片段的设置代码:

           JAXBContext jc = JAXBContext.newInstance( "com.acme.foo" );
           Unmarshaller u = jc.createUnmarshaller();
           Object element = u.unmarshal( new File( "foo.xml" ) );
           Marshaller m = jc.createMarshaller();
        

    编组文件:

           OutputStream os = new FileOutputStream( "nosferatu.xml" );
           m.marshal( element, os );
        

    编组到SAX ContentHandler:

           // assume MyContentHandler instanceof ContentHandler
           m.marshal( element, new MyContentHandler() );
        

    编组到DOM节点:

           DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
           dbf.setNamespaceAware(true);
           DocumentBuilder db = dbf.newDocumentBuilder();
           Document doc = db.newDocument();
    
           m.marshal( element, doc );
        

    编组到java.io.OutputStream:

           m.marshal( element, System.out );
        

    编组到java.io.Writer:

           m.marshal( element, new PrintWriter( System.out ) );
        

    编组到javax.xml.transform.SAXResult:

           // assume MyContentHandler instanceof ContentHandler
           SAXResult result = new SAXResult( new MyContentHandler() );
    
           m.marshal( element, result );
        

    编组到javax.xml.transform.DOMResult:

           DOMResult result = new DOMResult();
    
           m.marshal( element, result );
        

    编组到javax.xml.transform.StreamResult:

           StreamResult result = new StreamResult( System.out );
    
           m.marshal( element, result );
        

    编组到javax.xml.stream.XMLStreamWriter:

           XMLStreamWriter xmlStreamWriter =
               XMLOutputFactory.newInstance().createXMLStreamWriter( ... );
    
           m.marshal( element, xmlStreamWriter );
        

    编组到javax.xml.stream.XMLEventWriter:

           XMLEventWriter xmlEventWriter =
               XMLOutputFactory.newInstance().createXMLEventWriter( ... );
    
           m.marshal( element, xmlEventWriter );
        

    编组基于JAXB元素的内容树

    The first parameter of the overloaded Marshaller.marshal(java.lang.Object, ...) methods must be a JAXB element as computed by JAXBIntrospector.isElement(java.lang.Object); otherwise, a Marshaller.marshal method must throw a MarshalException. There exist two mechanisms to enable marshalling an instance that is not a JAXB element. One method is to wrap the instance as a value of a JAXBElement, and pass the wrapper element as the first parameter to a Marshaller.marshal method. For java to schema binding, it is also possible to simply annotate the instance's class with @ XmlRootElement.

    编码

    By default, the Marshaller will use UTF-8 encoding when generating XML data to a java.io.OutputStream, or a java.io.Writer. Use the setProperty API to change the output encoding used during these marshal operations. Client applications are expected to supply a valid character encoding name as defined in the W3C XML 1.0 Recommendation and supported by your Java Platform.

    验证和成型

    Client applications are not required to validate the Java content tree prior to calling any of the marshal API's. Furthermore, there is no requirement that the Java content tree be valid with respect to its original schema in order to marshal it back into XML data. Different JAXB Providers will support marshalling invalid Java content trees at varying levels, however all JAXB Providers must be able to marshal a valid content tree back to XML data. A JAXB Provider must throw a MarshalException when it is unable to complete the marshal operation due to invalid content. Some JAXB Providers will fully allow marshalling invalid content, others will fail on the first validation error.

    Even when schema validation is not explictly enabled for the marshal operation, it is possible that certain types of validation events will be detected during the operation. Validation events will be reported to the registered event handler. If the client application has not registered an event handler prior to invoking one of the marshal API's, then events will be delivered to a default event handler which will terminate the marshal operation after encountering the first error or fatal error. Note that for JAXB 2.0 and later versions, DefaultValidationEventHandler is no longer used.

    支持的属性

    All JAXB Providers are required to support the following set of properties. Some providers may support additional properties.

    jaxb.encoding - value must be a java.lang.String
    The output encoding to use when marshalling the XML data. The Marshaller will use "UTF-8" by default if this property is not specified.
    jaxb.formatted.output - value must be a java.lang.Boolean
    This property controls whether or not the Marshaller will format the resulting XML data with line breaks and indentation. A true value for this property indicates human readable indented xml data, while a false value indicates unformatted xml data. The Marshaller will default to false (unformatted) if this property is not specified.
    jaxb.schemaLocation - value must be a java.lang.String
    This property allows the client application to specify an xsi:schemaLocation attribute in the generated XML data. The format of the schemaLocation attribute value is discussed in an easy to understand, non-normative form in Section 5.6 of the W3C XML Schema Part 0: Primer and specified in Section 2.6 of the W3C XML Schema Part 1: Structures.
    jaxb.noNamespaceSchemaLocation - value must be a java.lang.String
    This property allows the client application to specify an xsi:noNamespaceSchemaLocation attribute in the generated XML data. The format of the schemaLocation attribute value is discussed in an easy to understand, non-normative form in Section 5.6 of the W3C XML Schema Part 0: Primer and specified in Section 2.6 of the W3C XML Schema Part 1: Structures.
    jaxb.fragment - value must be a java.lang.Boolean
    This property determines whether or not document level events will be generated by the Marshaller. If the property is not specified, the default is false. This property has different implications depending on which marshal api you are using - when this property is set to true:

    元帅事件回调

    "The Marshaller 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 marshalling. 'External listeners' allow for centralized processing of marshal 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 signatures:

       // Invoked by Marshaller after it has created an instance of this object.
       boolean beforeMarshal(Marshaller);
    
       // Invoked by Marshaller after it has marshalled all properties of this object.
       void afterMarshal(Marshaller);
     
    The class defined event 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 Marshaller.Listener instance with a setListener(Listener). The external listener receives all callback events, allowing for more centralized processing than per class defined callback methods.

    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 Marshaller.Listener.beforeMarshal(Object) and Marshaller.Listener.afterMarshal(Object).

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

    从以下版本开始:
    1.6,JAXB 1.0
    另请参见:
    JAXBContextValidatorUnmarshaller
    • 字段详细信息

      • JAXB_ENCODING

        static final String JAXB_ENCODING
        用于在编组的XML数据中指定输出编码的属性的名称。
        另请参见:
        Constant Field Values
      • JAXB_FORMATTED_OUTPUT

        static final String JAXB_FORMATTED_OUTPUT
        用于指定编组的XML数据是否使用换行符和缩进格式化的属性的名称。
        另请参见:
        Constant Field Values
      • JAXB_SCHEMA_LOCATION

        static final String JAXB_SCHEMA_LOCATION
        用于指定要排列在编组XML输出中的xsi:schemaLocation属性值的属性名称。
        另请参见:
        Constant Field Values
      • JAXB_NO_NAMESPACE_SCHEMA_LOCATION

        static final String JAXB_NO_NAMESPACE_SCHEMA_LOCATION
        用于指定要排列在编组XML输出中的xsi:noNamespaceSchemaLocation属性值的属性名称。
        另请参见:
        Constant Field Values
      • JAXB_FRAGMENT

        static final String JAXB_FRAGMENT
        用于指定编组器是否生成文档级事件(即调用startDocument或endDocument)的属性的名称。
        另请参见:
        Constant Field Values
    • 方法详细信息

      • marshal

        void marshal​(Object jaxbElement,
                     File output)
              throws JAXBException
        将根据 jaxbElement的内容树 jaxbElement到一个文件中。
        参数
        jaxbElement - 要编组的内容树的根。
        output - 要写入的文件。 如果这个文件已经存在,它将被覆盖。
        异常
        JAXBException - 如果在编组过程中发生意外问题。
        MarshalException - 如果ValidationEventHandler从其handleEvent方法返回false,或者Marshaller无法编组jaxbElement (或任何可从jaxbElement可访问的对象)。 参见Marshalling a JAXB element
        IllegalArgumentException - 如果任何方法参数为空
        从以下版本开始:
        1.6,JAXB 2.1
      • setProperty

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

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

        void setEventHandler​(ValidationEventHandler handler)
                      throws JAXBException
        允许应用程序注册验证事件处理程序。

        如果在任何元帅API的调用期间遇到任何验证错误,JAXB提供者将调用验证事件处理程序。 如果客户端应用程序在调用其中一个元数据方法之前没有注册验证事件处理程序,则验证事件将由默认事件处理程序处理,该事件处理程序将在遇到第一个错误或致命错误后终止元组操作。

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

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

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

        void setAttachmentMarshaller​(AttachmentMarshaller am)

        关联使XML文档中的二进制数据能够以XML二进制优化的附件传输的上下文。 附件由XML文档内容模型通过存储在xml文档中的content-id URI(cid)引用引用。

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

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

        该方法允许调用者在编组的XML中验证编组的XML。

        最初此属性设置为null

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

        Schema getSchema​()
        获取用于执行组织时间验证的JAXP 1.3 Schema对象。 如果在编组器中没有设置Schema,则该方法将返回null,表示将不执行组织时间验证。
        结果
        用于执行组织时间验证的Schema对象,如果不存在则使用null。
        异常
        UnsupportedOperationException - 如果在引用JAXB 1.0映射类的JAXBContext创建的Marshaller上调用此方法,则可能会抛出
        从以下版本开始:
        1.6,JAXB 2.0
      • setListener

        void setListener​(Marshaller.Listener listener)

        注册元帅事件回调Marshaller.Listener与这Marshaller

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

        参数
        listener - 实现Marshaller.Listener的类的实例
        从以下版本开始:
        1.6,JAXB 2.0