开发者

How do I create child elements using msxml parser?

I have a users.xml

<?xml version="1.0"?>
<Data>
    <Users>
        <User name="xyz" email="xyz@xyz.com">
                    <Tasks/>
        </User>
    </Users>
</Data>

I have got a reference to Users element using the following code

IXMLDOMDocumentPtr pXMLDom;

// code to load the xml dox

IXMLDOMElementPtr pXMLDocElement = NULL;
IXM开发者_如何转开发LDOMNodeListPtr pXMLUsers = NULL;

//gets <Data>
pXMLDocElement = pXMLDom->GetdocumentElement();

//gets <Users>
pXMLUsers = pXMLDocElement->childNodes;

Now how do I create a child element User in Users element.

I have tried using createElement() on pXMLUsers, but it says IXMLDOMNodeListPtr has no member appendChild.

I don't know how to create a new element.

Thanks.


You cannot use the IXMLDOMNodeListPtr to append a child - it's just for iterating existing children.

You can use the IXMLDOMElementPtr directly to call pXMLDocElement->appendChild() to add a child element in your Document.


Ok, I've found a solution, thanks to TERACytE

IXMLDOMDocumentPtr pXMLDom;

// code to load the xml dox

//Creating <User>
MSXML2::IXMLDOMElementPtr pUser = pXMLDom->createNode(NODE_ELEMENT, "User", "");

//Creating <User name="">
MSXML2::IXMLDOMAttributePtr pName = pXMLDom->createAttribute("name");
pName->value = name;

//Creating <User email="">
MSXML2::IXMLDOMAttributePtr pEmail = pXMLDom->createAttribute("email");
pEmail->value = email;

//Adding name attrib to <User>
pUser->setAttributeNode(pName);

//Adding email attrib to <User>
pUser->setAttributeNode(pEmail);

//Creating <Tasks>
MSXML2::IXMLDOMElementPtr pTasks = pXMLDom->createNode(NODE_ELEMENT, "Tasks", "");

//Creating <Task>
MSXML2::IXMLDOMElementPtr pTask = pXMLDom->createNode(NODE_ELEMENT, "Task", "");

//Creating <Task name="">
MSXML2::IXMLDOMAttributePtr pTName = pXMLDom->createAttribute("name");
pTName->value = task;

//Creating <User status="">
MSXML2::IXMLDOMAttributePtr pStatus = pXMLDom->createAttribute("status");
pStatus->value = status;

//Adding name attrib to <User>
pTask->setAttributeNode(pTName);

//Adding status attrib to <User>
pTask->setAttributeNode(pStatus);

//Adding <Task> to <Tasks>
pTasks->appendChild(pTask);

//Adding <Tasks> to <User>
pUser->appendChild(pTasks);

//Selecting <Users>
MSXML2::IXMLDOMNodePtr pUsers = pXMLDom->selectSingleNode("/Data/Users");

//Adding <User> to <Users>
pUsers->appendChild(pUser);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜