如何使用StAX添加架构位置

Lar*_*ars 7 java xml stax

我正在使用StAX,我想在我的xml文件中添加一个模式位置.实现这一目标的最佳方法是什么?

Max*_*fer 10

如果你使用XMLStreamWriter,你可以使用writeNamespace()writeAttribute()(或只是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();
Run Code Online (Sandbox Code Playgroud)

输出:

<?xml version="1.0" ?>
<YourRootElement xmlns:xsi="http://www.w3.org/2000/10/XMLSchema-instance" xsi:noNamespaceSchemaLocation="path_to_your.xsd"></YourRootElement>
Run Code Online (Sandbox Code Playgroud)

因为XMLEventWriter,你应该能够add()通过一个createAttribute().

此致,Max

  • 这对我有用,但XML我的XML没有完全验证.为了解决我的验证问题,我需要指定一个更新的模式实例:`http:// www.w3.org/2001/XMLSchema-instance`. (3认同)