简体   繁体   中英

C/C++ with libxml adding namespace to Child Element not root Element

i try to create a simple XML File with libxml Libraries C/C++.

#include <libxml/tree.h>

int main()
{

xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
xmlNodePtr root = xmlNewNode(NULL,BAD_CAST "BookingUpdate");

xmlDocSetRootElement(doc,root);
//Create new Namespaces
xmlNsPtr ns = xmlNewNs (root, BAD_CAST"http://www.systems.com/XMLSchema/BUM/TriggerBookingUpdate/2_0", BAD_CAST "");
xmlNsPtr ns1 = xmlNewNs (root, BAD_CAST"http://www.systems.com/XMLSchema/common/header/1_1", BAD_CAST "ns1");
xmlNsPtr xsi = xmlNewNs (root, BAD_CAST"http://www.w3.org/2001/XMLSchema-instance", BAD_CAST "xsi");

//Set the new namespace on root
xmlSetNs(root,ns1);

// Create a new Element
xmlNewChild(root,NULL,BAD_CAST"InterfaceHeader", BAD_CAST"Value");


xmlDocFormatDump(stdout,doc,1);
xmlFreeDoc(doc);
return 0;
}

Result: Root Element is created with namespace

<?xml version="1.0"?> 
<ns1:BookingUpdate
     xmlns:="http://www.systems.com/XMLSchema/BUM/TriggerBookingUpdate/2_0"
     xmlns:ns1="http://www.systems.com/XMLSchema/common/header/1_1"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">  
     <ns1:InterfaceHeader>
          Value
      </ns1:InterfaceHeader>
</ns1:BookingUpdate>

I wish to have a Result Root Element without any namespace but only Child Element with corresponding namespace

<?xml version="1.0"?>
<BookingUpdate xmlns:="http://www.systems.com/XMLSchema/BUM/TriggerBookingUpdate/2_0" xmlns:ns1="http://www.systems.com/XMLSchema/common/header/1_1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <ns1:InterfaceHeader>
          Value
      </ns1:InterfaceHeader>
</BookingUpdate>

How can I get this?

Thank you

I have found a Solution myself

#include <libxml/tree.h>

int main()
{
xmlNodePtr child1;
xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0");
xmlNodePtr root = xmlNewNode(NULL,BAD_CAST "BookingUpdate");

xmlDocSetRootElement(doc,root);
//Create namespaces
xmlNsPtr ns = xmlNewNs (root, BAD_CAST"http://www.systems.com/XMLSchema/BUM/TriggerBookingUpdate/2_0", BAD_CAST "");
xmlNsPtr ns1 = xmlNewNs (root, BAD_CAST"http://www.systems.com/XMLSchema/common/header/1_1", BAD_CAST "ns1");
xmlNsPtr xsi = xmlNewNs (root, BAD_CAST"http://www.w3.org/2001/XMLSchema-instance", BAD_CAST "xsi");

//Set namespace on root
//xmlSetNs(root,ns1);

// Create a new Element
child1=xmlNewChild(root,NULL,BAD_CAST"InterfaceHeader", BAD_CAST"Value");
xmlSetNs(child1, ns1);

xmlDocFormatDump(stdout,doc,1);
xmlFreeDoc(doc);
return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM