Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple XML namespaces in xerces

I need to create XML files which contain multiple namespaces. I create the root element with a default namespace, and add another namespace ("otherNS") with setAttribute().

The problem is, that when i insert an element (with createElement()) which is prefixed with "otherNS", xerces adds an empty namespace attribute. when I use createElementNS() and explicitly state the otherNS URI, xerces adds the full URI attribute. In my understanding of XML namespaces, both is wrong. (Also the examples in http://www.w3schools.com/Xml/xml_namespaces.asp do not repeat the namespace attributes in each element).

This is an example output:

<?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>

And this is the code:

       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);

My questions are:

  1. Is my usage of the Xerces API correct? Do I maybe have to add the second namespace differently, it seems that xerces does not recognize it.
  2. Are there maybe any features of the DOMLSSerializer class, which change that behaviour, so far I have not found any.
like image 693
dischoen Avatar asked Oct 15 '25 03:10

dischoen


1 Answers

I got the solution on the Xerces mailing list:

Replace:

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

with:

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

The reason: the namespace definition itself must be located in the xmlns namespace, so the setAttributeNS() method has to be used.

like image 120
dischoen Avatar answered Oct 17 '25 17:10

dischoen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!