我尝试使用libxml Libraries C / C ++创建一个简单的XML文件。
#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;
}
结果:使用命名空间
创建根元素<?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>
我希望结果根元素没有任何名称空间,但只有具有相应名称空间的子元素
<?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>
我怎么能得到这个?
谢谢
答案 0 :(得分:0)
我自己找到了一个解决方案
#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;
}