JAXB generic @XmlValue

前端 未结 4 828
暖寄归人
暖寄归人 2021-02-06 06:00

The goal is to produce the following XML with JAXB


   string data
   binary data

         


        
4条回答
  •  心在旅途
    2021-02-06 06:50

    I couldn't get @XmlValue working as I always got NullPointerException along the way—not sure why. I came up with something like the following instead.

    Drop your Bar class entirely, because, as you want it to be able to contain anything you can simply represent it with Object.

    @XmlRootElement(name = "foo", namespace = "http://test.com")
    @XmlType(name = "Foo", namespace = "http://test.com")
    public class Foo {
    
      @XmlElement(name = "bar")
      public List bars = new ArrayList<>();
    
      public Foo() {}
    }
    
    
    

    Without telling JAXB which namespaces your types are using every bar element inside a foo would contain separate namespace declarations and stuff—the package-info.java and all the namespace stuff serves only fancification purposes only.

    @XmlSchema(attributeFormDefault = XmlNsForm.QUALIFIED,
               elementFormDefault = XmlNsForm.QUALIFIED,
               namespace = "http://test.com",
               xmlns = {
                   @XmlNs(namespaceURI = "http://test.com", prefix = ""),
                   @XmlNs(namespaceURI = "http://www.w3.org/2001/XMLSchema-instance", prefix = "xsi"),
                   @XmlNs(namespaceURI = "http://www.w3.org/2001/XMLSchema", prefix = "xs")})
    package test;
    
    import javax.xml.bind.annotation.XmlNs;
    import javax.xml.bind.annotation.XmlNsForm;
    import javax.xml.bind.annotation.XmlSchema;
    

    Running this simple test would spout-out something similar to your XML snippet.

    public static void main(String[] args) throws JAXBException {
      JAXBContext context = JAXBContext.newInstance(Foo.class);
    
      Foo foo = new Foo();
      foo.bars.add("a");
      foo.bars.add("b".getBytes());
    
      Marshaller marshaller = context.createMarshaller();
      marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
      marshaller.marshal(foo, System.out);
    }
    

    Output:

    
    
        a
        Yg==
    
    

    提交回复
    热议问题