Search code examples
xmlxml-serializationstax

How to write @xml:space="preserve" with Stax


I use stax to write a XML file.

My question is how can I add the attribute xml:space="preserve" to my elements?

  • Do I need to declare the xml prefix? AFAIK, it is normally not necessay.
    • If I don't declare, stax complains that a preferred prefix cannot be null ( javax.xml.stream.XMLStreamException: Prefix cannot be null)
    • If I declare the prefix with setPrefix("xml", "http://www.w3.org/1998/xml") on my XMLStreamWriter, it seems to have no effect. In debug mode, I see that the nsmap of the XMLStreamWriter has no entry for "xml"
  • The exception is raised when I write the attribute with writeAttribe("http://www.w3.org/1998/xml", "space", "preserve"). Is there a specific method for this instead?

Solution

  • I found a work around:

    writeAttribute("xml:space", "preserve")
    

    but this is a non-sense because xml:space is not a local name, is it?