Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a schema location with StAX

Tags:

java

xml

stax

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

like image 253
Lars Avatar asked Jan 27 '12 10:01

Lars


1 Answers

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

like image 163
Max Avatar answered Oct 06 '22 22:10

Max