【问题标题】:Multiple XML namespaces in xercesxerces 中的多个 XML 命名空间
【发布时间】:2015-11-06 11:48:51
【问题描述】:

我需要创建包含多个命名空间的 XML 文件。 我使用默认命名空间创建根元素,然后添加另一个 带有 setAttribute() 的命名空间(“otherNS”)。

问题是,当我插入一个以“otherNS”为前缀的元素(使用 createElement())时, xerces 添加了一个空的命名空间属性。当我使用 createElementNS() 并明确声明 otherNS URI 时,xerces 添加了完整的 URI 属性。 在我对 XML 命名空间的理解中,两者都是错误的。 (还有例子 http://www.w3schools.com/Xml/xml_namespaces.asp 不要在每个元素中重复命名空间属性)。

这是一个示例输出:

<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
  <company xmlns="http://default.namespace.org/NS" xmlns:otherNS="http://other.namespace.org/ONS">
    <otherNS:product xmlns="">Xerces-C</otherNS:product>
    <otherNS:category xmlns:otherNS="http://other.namespace.org/ONS" idea="great">XML Parsing Tools</otherNS:category>
    <developedBy xmlns="">Apache Software Foundation</developedBy>
  </company>

这是代码:

       DOMDocument* doc = impl->createDocument(
           X("http://default.namespace.org/NS"),
           X("company"),                        
           0);                                  

       DOMElement* rootElem = doc->getDocumentElement();
       rootElem->setAttribute(
           X("xmlns:otherNS"),
           X("http://other.namespace.org/ONS"));


       DOMElement*  prodElem = doc->createElement(X("otherNS:product"));
       rootElem->appendChild(prodElem);

       DOMText*    prodDataVal = doc->createTextNode(X("Xerces-C"));
       prodElem->appendChild(prodDataVal);

       DOMElement*  catElem = doc->createElementNS(
           X("http://other.namespace.org/ONS"),
           X("otherNS:category"));
       rootElem->appendChild(catElem);

我的问题是:

  1. 我对 Xerces API 的使用是否正确?我是否可能需要以不同的方式添加第二个命名空间,xerces 似乎无法识别它。
  2. DOMLSSerializer 类是否有任何特性可以改变这种行为,到目前为止我还没有发现任何特性。

【问题讨论】:

    标签: c++ xml xml-namespaces xerces


    【解决方案1】:

    我在Xerces mailing list上得到了解决方案:

    替换:

        rootElem->setAttribute(
            X("xmlns:otherNS"),
            X("http://other.namespace.org/ONS"));
    

    与:

          rootElem->setAttributeNS(X("http://www.w3.org/2000/xmlns/"),
                                   X("xmlns:otherNS"),
                                   X("http://other.namespace.org/ONS"));
    

    原因:命名空间定义本身必须位于xmlns命名空间中,所以必须使用setAttributeNS()方法。

    【讨论】:

      猜你喜欢
      • 2014-04-19
      • 1970-01-01
      • 2020-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-30
      • 2012-08-15
      • 2017-04-29
      相关资源
      最近更新 更多