How to deal with JAXB ComplexType with MixedContent data?

前端 未结 2 1025
说谎
说谎 2020-12-01 16:59

I got this XML structure:


  0.00
  
     17.5% No         


        
相关标签:
2条回答
  • 2020-12-01 17:36

    As you mentioned you need to add the mixed attribute to indicate that your type supports mixed content. Without this specified your XML content is invalid:

    <xsd:complexType name="TaxDescriptionType" mixed="true">
        <xsd:sequence>
            <xsd:element name="ShortName" type="xsd:string" />
        </xsd:sequence>
        <xsd:attribute ref="xml:lang" />
    </xsd:complexType>
    

    The generated TaxDescriptionType class will have the following property. Essentially this means that all of the non-attribute content will be stored in a List. This is necessary because you need a mechanism that indicates where the text nodes are wrt the element content.

    @XmlElementRef(name = "ShortName", namespace = "http://www.example.org/schema", type = JAXBElement.class)
    @XmlMixed
    protected List<Serializable> content;
    

    You will populate this list with instances of String (representing text nodes) and JAXBElement (representing element content).


    ALTERNATIVELY

    Mixed content generally makes life more complicated than it needs to be. If possible I would recommend an alternate XML representation.

    <Tax>
      <Money currency="USD">0.00</Money>
      <Description xml:lang="en" ShortName="vatspecial">
        17.5% Non-Recoverable
      </Description>
    </Tax>
    

    Or

    <Tax>
      <Money currency="USD">0.00</Money>
      <Description xml:lang="en">
        <LongName>17.5% Non-Recoverable</LongName>
        <ShortName>vatspecial</ShortName>
      </Description>
    </Tax>
    
    0 讨论(0)
  • 2020-12-01 17:52

    With mixed=true, in ObjectFactory there should be a function like JAXBElement<ShortNameType> createTaxDescriptionTypeShortNameType(ShortNameType), which generates the serializable element for you.

     @XmlElementDecl(namespace = "", name = "shortnametype", scope = TaxDescriptionType.class)
        public JAXBElement<ShortNameType> createTaxDescriptionTypeShortNameType(ShortNameType value) {
            return new JAXBElement<ShortNameType>(new QName("", "shortnametype"), ShortNameType.class, TaxDescriptionType.class, value);
     }
    
    0 讨论(0)
提交回复
热议问题