2

I am looking to control where JAXB generates the xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" declaration when marshalling to XML. I've seen solutions like this to add it to the root element using the JAXB_SCHEMA_LOCATION property, however I don't want it on the root node, I want it somewhere in between. Here's what I've got:

@XmlRootElement(name = "RootNode")
@XmlAccessorType(XmlAccessType.NONE)
public class RootNode {
    @XmlElement(name = "IntermediateNode")
    private IntermediateNode intermediateNode;

    //getter & setter
}

@XmlAccessorType(XmlAccessType.NONE)
public class IntermediateNode {
    @XmlElement(name = "MyEntity")
    private MyEntity myEntity;

    //getter and setter
}

@XmlAccessorType(XmlAccessType.NONE)
public class MyEntity {
    @XmlElement(name = "Name")
    private String name;

    @XmlElement(name = "Title", nillable = true)
    private String title;

    //getters and setters
}

Serialize like:

MyEntity myEntity = new MyEntity();
myEntity.setName("George");
myEntity.setTitle(null);

IntermediateNode intNode = new IntermediateNode();
intNode.setMyEntity(myEntity);

RootNode rootNode = new RootNode();
rootNode.setIntermediateNode(intNode);

JAXBContext context = JAXBContext.newInstance(RootNode.class);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(rootNode, System.out);

Produces XML like:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<RootNode>
    <IntermediateNode>
        <MyEntity>
            <Name>George</Name>
            <Title xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
        </MyEntity>
    </IntermediateNode>
</RootNode>

But what I want is:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<RootNode>
    <IntermediateNode xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <MyEntity>
            <Name>George</Name>
            <Title xsi:nil="true"/>
        </MyEntity>
    </IntermediateNode>
</RootNode>

I even tried moving my IntermediateNode and MyEntity classes into their own package with a package-info.java like this, but that just rolled the xmlns:xsi up to the root element.

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

package com.example.intermediate;

Is it possible to get what I want?

Community
  • 1
  • 1
schmimd04
  • 1,444
  • 3
  • 14
  • 23

0 Answers0