Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6866359
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T03:10:25+00:00 2026-05-27T03:10:25+00:00

I’m using JAXB with Scala, my marshalling code looks like this: def marshalToXml(): String

  • 0

I’m using JAXB with Scala, my marshalling code looks like this:

def marshalToXml(): String = {
  val context = JAXBContext.newInstance(this.getClass())
  val writer = new StringWriter
  context.createMarshaller.marshal(this, writer)
  writer.toString()
}

Then for my nullable elements I’m using the annotation @XmlElement(nillable = true) as per JAXB Marshalling with null fields. This gives me XML output like so:

<name>Alex Dean</name>
<customerReference xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
<quantity>1</quantity>
<createdAt>2011-05-14T00:00:00+03:00</createdAt>

This is a good start but what I’d really like to marshal for these fields is:

<name>Alex Dean</name>
<customerReference nil="true"/>
<quantity type="integer">1</quantity>
<createdAt type="datetime">2011-05-14T00:00:00+03:00</createdAt>

In other words, I would like to remove the namespace attributes and prefixes, and add in explicit XML datatype attributes for all but strings. It’s probably quite simple to do but I can’t seem to find how in the JAXB documentation.

Any help gratefully received!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T03:10:26+00:00Added an answer on May 27, 2026 at 3:10 am

    You could use JAXB with a StAX parser and do the following:

    Customer

    Each property in your domain model will be mapped with @XmlElement(nillable=true, type=Object.class). Setting the type=Object.class will force an xsi:type attribute to be written out.

    package forum8198945;
    
    import java.util.Date;  
    import javax.xml.bind.annotation.*;
    
    @XmlRootElement
    public class Customer {
    
        private String name;
        private Customer customerReference;
        private Integer quantity;
        private Date createdAt;
    
        @XmlElement(nillable=true, type=Object.class)
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        @XmlElement(nillable=true, type=Object.class)
        public Customer getCustomerReference() {
            return customerReference;
        }
    
        public void setCustomerReference(Customer customerReference) {
            this.customerReference = customerReference;
        }
    
        @XmlElement(nillable=true, type=Object.class)
        public Integer getQuantity() {
            return quantity;
        }
    
        public void setQuantity(Integer quantity) {
            this.quantity = quantity;
        }
    
        @XmlElement(nillable=true, type=Object.class)
        public Date getCreatedAt() {
            return createdAt;
        }
    
        public void setCreatedAt(Date createdAt) {
            this.createdAt = createdAt;
        }
    
    }
    

    XMLStreamWriterWrapper

    We will write a create a wrapper for an XMLStreamWriter that strips off all the information we do not want written to XML.

    package forum8198945;
    
    import javax.xml.namespace.NamespaceContext;
    import javax.xml.stream.XMLStreamException;
    import javax.xml.stream.XMLStreamWriter;
    
    public class XMLStreamWriterWrapper implements XMLStreamWriter {
    
        private XMLStreamWriter xmlStreamWriter;
    
        public XMLStreamWriterWrapper(XMLStreamWriter xmlStreamWriter) {
            this.xmlStreamWriter = xmlStreamWriter;
        }
    
        public void writeStartElement(String localName) throws XMLStreamException {
            xmlStreamWriter.writeStartElement(localName);
        }
    
        public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException {
            xmlStreamWriter.writeStartElement(namespaceURI, localName);
        }
    
        public void writeStartElement(String prefix, String localName, String namespaceURI) throws XMLStreamException {
            xmlStreamWriter.writeStartElement(prefix, localName, namespaceURI);
        }
    
        public void writeEmptyElement(String namespaceURI, String localName) throws XMLStreamException {
            xmlStreamWriter.writeEmptyElement(namespaceURI, localName);
        }
    
        public void writeEmptyElement(String prefix, String localName, String namespaceURI) throws XMLStreamException {
            xmlStreamWriter.writeEmptyElement(prefix, localName, namespaceURI);
        }
    
        public void writeEmptyElement(String localName) throws XMLStreamException {
            xmlStreamWriter.writeEmptyElement(localName);
        }
    
        public void writeEndElement() throws XMLStreamException {
            xmlStreamWriter.writeEndElement();
        }
    
        public void writeEndDocument() throws XMLStreamException {
            xmlStreamWriter.writeEndDocument();
        }
    
        public void close() throws XMLStreamException {
            xmlStreamWriter.close();
        }
    
        public void flush() throws XMLStreamException {
            xmlStreamWriter.flush();
        }
    
        public void writeAttribute(String localName, String value) throws XMLStreamException {
            xmlStreamWriter.writeAttribute(localName, value);
        }
    
        public void writeAttribute(String prefix, String namespaceURI, String localName, String value) throws XMLStreamException {
            if("http://www.w3.org/2001/XMLSchema-instance".equals(namespaceURI)) {
                int colonIndex = value.indexOf(':');
                if(colonIndex > -1) {
                    value = value.substring(colonIndex + 1);
                }
                xmlStreamWriter.writeAttribute(localName, value);
            } else {
                xmlStreamWriter.writeAttribute(prefix, namespaceURI, localName, value);
            }
        }
    
        public void writeAttribute(String namespaceURI, String localName, String value) throws XMLStreamException {
            if("http://www.w3.org/2001/XMLSchema-instance".equals(namespaceURI)) {
                int colonIndex = value.indexOf(':');
                if(colonIndex > -1) {
                    value = value.substring(colonIndex + 1);
                }
                xmlStreamWriter.writeAttribute(localName, value);
            } else {
                xmlStreamWriter.writeAttribute(namespaceURI, localName, value);
            }
        }
    
        public void writeNamespace(String prefix, String namespaceURI) throws XMLStreamException {
            if(!"http://www.w3.org/2001/XMLSchema-instance".equals(namespaceURI) && !"http://www.w3.org/2001/XMLSchema".equals(namespaceURI)) {
                xmlStreamWriter.writeNamespace(prefix, namespaceURI);
            }
        }
    
        public void writeDefaultNamespace(String namespaceURI) throws XMLStreamException {
            if(!"http://www.w3.org/2001/XMLSchema-instance".equals(namespaceURI)) {
                xmlStreamWriter.writeDefaultNamespace(namespaceURI);
            }
        }
    
        public void writeComment(String data) throws XMLStreamException {
            // TODO Auto-generated method stub
        }
    
        public void writeProcessingInstruction(String target) throws XMLStreamException {
            // TODO Auto-generated method stub
        }
    
        public void writeProcessingInstruction(String target, String data) throws XMLStreamException {
            // TODO Auto-generated method stub
        }
    
        public void writeCData(String data) throws XMLStreamException {
            // TODO Auto-generated method stub
        }
    
        public void writeDTD(String dtd) throws XMLStreamException {
            // TODO Auto-generated method stub
        }
    
        public void writeEntityRef(String name) throws XMLStreamException {
            // TODO Auto-generated method stub
        }
    
        public void writeStartDocument() throws XMLStreamException {
            xmlStreamWriter.writeStartDocument();
        }
    
        public void writeStartDocument(String version) throws XMLStreamException {
            xmlStreamWriter.writeStartDocument(version);
        }
    
        public void writeStartDocument(String encoding, String version) throws XMLStreamException {
            xmlStreamWriter.writeStartDocument(encoding, version);
        }
    
        public void writeCharacters(String text) throws XMLStreamException {
            xmlStreamWriter.writeCharacters(text);
        }
    
        public void writeCharacters(char[] text, int start, int len) throws XMLStreamException {
            xmlStreamWriter.writeCharacters(text, start, len);
        }
    
        public String getPrefix(String uri) throws XMLStreamException {
            return xmlStreamWriter.getPrefix(uri);
        }
    
        public void setPrefix(String prefix, String uri) throws XMLStreamException {
            xmlStreamWriter.setPrefix(prefix, uri);
        }
    
        public void setDefaultNamespace(String uri) throws XMLStreamException {
            xmlStreamWriter.setDefaultNamespace(uri);
        }
    
        public void setNamespaceContext(NamespaceContext context) throws XMLStreamException {
            xmlStreamWriter.setNamespaceContext(context);
        }
    
        public NamespaceContext getNamespaceContext() {
            return xmlStreamWriter.getNamespaceContext();
        }
    
        public Object getProperty(String name) throws IllegalArgumentException {
            return xmlStreamWriter.getProperty(name);
        }
    
    }
    

    XMLStreamReaderWrapper

    We need to create a wrapper for XMLStreamReader that adds everything that we stripped off on the XMLStreamWriter. This is easier to do for XMLStreamReader since we can extend StreamReaderDelegate.

    package forum8198945;
    
    import javax.xml.stream.XMLStreamReader;
    import javax.xml.stream.util.StreamReaderDelegate;
    
    public class XMLStreamReaderWrapper extends StreamReaderDelegate {
    
        public XMLStreamReaderWrapper(XMLStreamReader xmlStreamReader) {
            super(xmlStreamReader);
        }
    
        @Override
        public String getAttributeNamespace(int index) {
            String attributeName = getAttributeLocalName(index);
            if("type".equals(attributeName) || "nil".equals(attributeName)) {
                return "http://www.w3.org/2001/XMLSchema-instance";
            }
            return super.getAttributeNamespace(index);
        }
    
    
    }
    

    Demo

    The following demonstrates how everything comes together:

    package forum8198945;
    
    import java.io.StringReader;
    import java.io.StringWriter;
    import java.util.Date;
    
    import javax.xml.bind.JAXBContext;
    import javax.xml.bind.Marshaller;
    import javax.xml.stream.XMLInputFactory;
    import javax.xml.stream.XMLOutputFactory;
    import javax.xml.stream.XMLStreamWriter;
    
    public class Demo {
    
        public static void main(String[] args) throws Exception {
            JAXBContext jc = JAXBContext.newInstance(Customer.class);
    
            Customer customer = new Customer();
            customer.setName("Alex Dean");
            customer.setCustomerReference(null);
            customer.setQuantity(1);
            customer.setCreatedAt(new Date());
    
            StringWriter stringWriter = new StringWriter();
            XMLOutputFactory xof = XMLOutputFactory.newFactory();
            XMLStreamWriter xsw = xof.createXMLStreamWriter(stringWriter);
            xsw = new XMLStreamWriterWrapper(xsw);
            Marshaller marshaller = jc.createMarshaller();
            marshaller.marshal(customer, xsw);
    
            String xml = stringWriter.toString();
            System.out.println(xml);
    
            XMLInputFactory xif = XMLInputFactory.newFactory();
            xif.createXMLStreamReader(new StringReader(xml));
    
            printValue(customer.getName());
            printValue(customer.getCustomerReference());
            printValue(customer.getQuantity());
            printValue(customer.getCreatedAt());
        }
    
        private static void printValue(Object value) {
            System.out.print(value);
            System.out.print(" ");
            if(null != value) {
                System.out.print(value.getClass());
            }
            System.out.println();
        }
    
    }
    

    Output

    <?xml version="1.0"?><customer><createdAt type="dateTime">2011-11-25T13:36:49.095</createdAt><customerReference nil="true"></customerReference><name type="string">Alex Dean</name><quantity type="int">1</quantity></customer>
    Alex Dean class java.lang.String
    null 
    1 class java.lang.Integer
    Fri Nov 25 13:36:49 EST 2011 class java.util.Date
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
For some reason, after submitting a string like this Jack’s Spindle from a text
I would like to count the length of a string with PHP. The string
I've got a string that has curly quotes in it. I'd like to replace
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString
Does anyone know how can I replace this 2 symbol below from the string
I have some data like this: 1 2 3 4 5 9 2 6
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
That's pretty much it. I'm using Nokogiri to scrape a web page what has

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.