2015-11-06 71 views
2

我需要创建包含多个名称空间的XML文件。 我使用默认名称空间创建根元素,并使用setAttribute()添加另一个 名称空间(“otherNS”)。xerces中的多个XML名称空间

问题是,当我插入一个前缀为“otherNS”的元素(带有createElement())时,xerces添加了一个空的名称空间属性。当我使用createElementNS()并显式声明其他的NS 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类的功能,它改变了这种行为,到目前为止我还没有找到任何功能。

回答

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()方法。