I questioned before about a similar problem in RapidXml, I want to know, now, the same but using Xerces-C.
I am working on a c++ application that needs to parse xml.
Consider the following:
xml file: file1.xml
<root>
<node1>value1</node1>
<node2>value2</node2>
</root>
xml file: file2.xml
<anotherroot>
<anothernode1>anothervalue1</anothernode1>
<anothernode2>anothervalue2</anothernode2>
</anotherroot>
my cpp file
using namespace xercesc;
// First tree
XercesDOMParser* parser1 = new XercesDOMParser();
parser1->parse("file1.xml"); // Loading xml and building tree (XercesDOMParser owns the document)
DOMDocument* doc1 = parser1->getDocument();
DOMElement* el1 = doc1->getDocumentElement(); // Getting root
// Second tree
XercesDOMParser* parser2 = new XercesDOMParser();
parser2->parse("file2.xml"); // Loading xml and building tree (X开发者_如何学编程ercesDOMParser owns the document)
DOMDocument* doc2 = parser2->getDocument();
DOMElement* el2 = doc2->getDocumentElement(); // Getting root
I would like to do this:
el2->appendChild(el1);
So that the final xml in the document doc2 is
<anotherroot>
<anothernode1>anothervalue1</anothernode1>
<anothernode2>anothervalue2</anothernode2>
<root>
<node1>value1</node1>
<node2>value2</node2>
</root>
</anotherroot>
But when doing so I get:
terminate called after throwing an instance of 'xercesc_3_1::DOMException' Aborted
I guess because the element I want to attach belongs to another tree. How can I achieve this result? The problem, basically, is that I have a tree and a string containing an xml segment. I NEED TO PARSE THE STRING get a DOM object representing that xml and attaching to a node of the other tree. The most important thing is that I have the string with the xml inside... I cannot bypass this important requirement. From a string, getting the dom and attaching it. It seems to be something impossible... possible?
How can I do this??? I really cannot accept the fact that Xerces-C programmers never figured such a scenario and did not provide a reasonable functionality to achieve such solution.
Maybe it would be enough even if I coult tell me whether there is a way of CHANGING THE NODE OWNERSHIP os a node or an element. You see, there is the WRONG_DOCUMENT_ERR which is raised when what I tried before is performed. Well, If the library provided a way to change the ownership of a node so that it belongs to another document, I would be all right and my problem would be solved!
Thankyou
DOMDocument::importNode is a DOM Level 2 function that was designed to solve this exact problem:
DOMElement * el1Imported = doc2->importNode(el1, true);
el2->appendChild(el1Imported); // element is now in right document
精彩评论