【问题标题】:Binding namespaces in Java's DOM API在 Java 的 DOM API 中绑定命名空间
【发布时间】:2014-04-23 15:24:52
【问题描述】:

目前我正在通过以下方式将命名空间添加到文档中:

node.getOwnerDocument().getDocumentElement()
    .setAttribute("xmlns:" + prefix, namespaceURI);

这个方法的问题是……

node.lookupPrefix(namespaceURI);

仍然返回null

另一种尝试:

node.getOwnerDocument().getDocumentElement()
.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, prefix, namespaceURI);

最终导致:

org.w3c.dom.DOMException: NAMESPACE_ERR: An attempt is made to create or change an object in a way which is incorrect with regard to namespaces.

有没有可行的方法?

【问题讨论】:

    标签: java xml dom xml-namespaces


    【解决方案1】:

    第二次尝试是朝着正确方向迈出的一步。缺少的部分(异常的原因)是您必须在属性中包含xmlns。所以“ns1”无效,但“xmlns:ns1”有效。

    (您可以使用字符串“xmlns”的常量来表示美点)。

    node.getOwnerDocument().getDocumentElement().setAttributeNS(
        XMLConstants.XMLNS_ATTRIBUTE_NS_URI,
        XMLConstants.XMLNS_ATTRIBUTE + ":" + prefix,
        namespaceURI);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-16
      • 2011-02-28
      • 2012-11-01
      • 2013-08-27
      相关资源
      最近更新 更多