【问题标题】:How to add a schema location with StAX如何使用 StAX 添加架构位置
【发布时间】:2012-02-20 08:41:11
【问题描述】:

我正在使用 StAX,我想将架构位置添加到我的 xml 文件中。实现这一目标的最佳方法是什么?

【问题讨论】:

    标签: java xml stax


    【解决方案1】:

    如果您使用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();
    

    输出:

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

    对于XMLEventWriter,您应该可以通过add()@createAttribute() 来完成。

    问候, 最大

    【讨论】:

    • 嗨 Max,我已经预料到了这个解决方案。感谢您的澄清。
    • 这对我有用,但是我的 XML 没有完全验证 XML。为了解决我的验证问题,我需要指定一个较新的模式实例:http://www.w3.org/2001/XMLSchema-instance
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-17
    • 2015-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多