【问题标题】:StaX's isRepairingNamespaces feature generates a prefix different to 'xml' for the XML namespaceStaX 的 isRepairingNamespaces 功能为 XML 命名空间生成一个不同于“xml”的前缀
【发布时间】:2012-04-10 03:54:55
【问题描述】:

我按如下方式创建序列化 XML:

XMLOutputFactory factory = XMLOutputFactory.newInstance();
factory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true);

StringWriter buffer = new StringWriter();
XMLStreamWriter writer = factory.createXMLStreamWriter(buffer);

writer.writeStartElement("doc");
writer.writeAttribute(javax.xml.XMLConstants.XML_NS_URI, "base", "/mydoc.xml");
writer.writeCharacters("Hello world");
writer.writeEndDocument();
writer.close();

// buffer now contains:
// <doc xmlns:zdef101282835="http://www.w3.org/XML/1998/namespace" zdef101282835:base="/mydoc.xml">Hello world</doc>

因此,修复命名空间功能为 http://www.w3.org/XML/1998/namespace 命名空间生成了除 xml 之外的前缀。

如果不是因为重新解析文档时返回的错误,我会很好。当我尝试解析生成的文档时,出现以下异常:

org.xml.sax.SAXParseException: The prefix "xml" cannot be bound to any namespace other than its usual namespace; neither can the namespace for "xml" be bound to any prefix other than "xml".

有没有办法配置XMLOutputFactory 以正确执行此操作?

就在您告诉我使用包含prefix 参数的writeAttribute 方法之前,我在对象之间传递SAX 事件,但不想知道它们是什么。这就是为什么我希望编组器为我处理命名空间......所以我不必在特定情况下为前缀是预先确定的给定命名空间编写。鉴于 xml 命名空间甚至不必定义(甚至可能不应该如此),写入 IS_REPAIRING_NAMESPACES 代码库将是一个简单的例外,不是吗?

感谢您的任何建议。

【问题讨论】:

    标签: java serialization marshalling xml-namespaces stax


    【解决方案1】:

    编写器只会“修复”未绑定到前缀的命名空间。添加

    writer.setPrefix("xml", XMLConstants.XML_NS_URI);
    

    在实际编写根元素之前解决问题。

    【讨论】:

      猜你喜欢
      • 2012-09-29
      • 1970-01-01
      • 1970-01-01
      • 2019-07-14
      • 1970-01-01
      • 1970-01-01
      • 2011-08-16
      • 1970-01-01
      • 2016-12-17
      相关资源
      最近更新 更多