7

I am using StAX and I want to add a schema location to my xml file. What is the best way to achieve this?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Lars
  • 320
  • 1
  • 4
  • 13

1 Answers1

10

If you use XMLStreamWriter, you can just use writeNamespace() and writeAttribute() (or just writeAttribute()).

XMLStreamWriter xmlStreamWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(System.out);
xmlStreamWriter.writeStartDocument();
xmlStreamWriter.writeStartElement("YourRootElement");
xmlStreamWriter.writeNamespace("xsi", "http://www.w3.org/2000/10/XMLSchema-instance");
xmlStreamWriter.writeAttribute("http://www.w3.org/2000/10/XMLSchema-instance", "noNamespaceSchemaLocation",
        "path_to_your.xsd");
xmlStreamWriter.writeEndElement();
xmlStreamWriter.flush();

Output:

<?xml version="1.0" ?>
<YourRootElement xmlns:xsi="http://www.w3.org/2000/10/XMLSchema-instance" xsi:noNamespaceSchemaLocation="path_to_your.xsd"></YourRootElement>

For XMLEventWriter, you should be able to do it by add()ing a createAttribute().

Regards, Max

Max
  • 1,000
  • 1
  • 11
  • 25
  • Hi Max, I already expected this solution. Thanks for the clarification. – Lars Jan 28 '12 at 20:54
  • 3
    This worked for me, but XML my XML didn't fully validate. To fix my validation problems, I needed to specify a newer schema instance as: `http://www.w3.org/2001/XMLSchema-instance`. – Muel Dec 05 '12 at 03:23