简体   繁体   中英

Add another XML file to existing XML file using MSXML C++

I am working on the project, where I am using MSXML parser to create and parse the XML documents. The existing implementation uses CMarkup and it has a function to add another XML document to existing document using addsubdoc(xmlfile) but When I am trying that with MSXML parser it is not happening.

Does anybody has a solution regarding it.

for example what I have tried:

CString str = L"<?xml version=\"1.0\" encoding=\"utf-16\"?>\r\n"
            L"<Book>"
            L"<Text>"
            L"<Name>CPP</Name>"
            L"<Author>Henry</Author>"
            L"</Text>"
            L"</Book>";
CString sub = L"<Text>"
              L"<Name>5656</Name>"
              L"<Author>Steve</Author>"
              L"</Text>"

The xml I want is:

<Book>
<Text>...</Text>
<Text>..New added..</Text>
</Book>

Now I want to add the sub to str in a way that it auto add under Book tag. SO I did:

pXMLDom1->loadXML(_bstr_t(str));
pXMLDom2->loadXML(_bstr_t(sub));
// To get root node
CString root = (LPCSTR)pXMLDom1->GetfirstChild()->baseName;
pXMLDom1->selectSingleNode(root)->appendChild(pXMLDom2);

but it does not adding the data.

EXAMPLE CODE to TEST:

#import <msxml6.dll>
#include "msxml2.h"
#include <iostream>
#include <atlstr.h>

void main()
{

MSXML2::IXMLDOMDocumentPtr pXMLDom1;
MSXML2::IXMLDOMDocumentPtr pXMLDom2;
HRESULT hr = pXMLDom.CreateInstance(__uuidof(MSXML2::DOMDocument60), NULL, CLSCTX_INPROC_SERVER);
HRESULT hr2 = pXMLDom2.CreateInstance(__uuidof(MSXML2::DOMDocument60), NULL, CLSCTX_INPROC_SERVER);

CString str = L"<?xml version=\"1.0\" encoding=\"utf-16\"?>\r\n"
              L"<Book>"
              L"<Text>"
              L"<Name>CPP</Name>"
              L"<Author>Henry</Author>"
              L"</Text>"
              L"</Book>";

CString sub = L"<Text>"
              L"<Name>5656</Name>"
              L"<Author>Steve</Author>"
              L"</Text>";

pXMLDom1->loadXML(_bstr_t(str));
pXMLDom2->loadXML(_bstr_t(sub));

printf("Dynamically created DOM:\n%s\n", static_cast<PCSTR>(pXMLDom1->xml));
printf("Dynamically created DOM:\n%s\n", static_cast<PCSTR>(pXMLDom2->xml));

// To get root node
CString root = (LPCSTR)pXMLDom1->GetfirstChild()->baseName;
pXMLDom1->selectSingleNode(root)->appendChild(pXMLDom2);

printf("Merged XML:\n%s\n", static_cast<PCSTR>(pXMLDom1->xml));
}

Try this:

pXMLDom1->documentElement->appendChild(pXMLDom2->documentElement)

Or, slightly modifying your code:

CString root = (LPCSTR)pXMLDom1->documentElement;
pXMLDom1->selectSingleNode(root)->appendChild(pXMLDom2->documentElement);

Also, note that pXMLDom1->GetfirstChild()->baseName gives you "xml" .

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