我有一个users.xml
<?xml version="1.0"?>
<Data>
<Users>
<User name="xyz" email="xyz@xyz.com">
<Tasks/>
</User>
</Users>
</Data>
我使用以下代码
引用了用户元素IXMLDOMDocumentPtr pXMLDom;
// code to load the xml dox
IXMLDOMElementPtr pXMLDocElement = NULL;
IXMLDOMNodeListPtr pXMLUsers = NULL;
//gets <Data>
pXMLDocElement = pXMLDom->GetdocumentElement();
//gets <Users>
pXMLUsers = pXMLDocElement->childNodes;
现在如何在用户元素中创建子元素用户。
我尝试在createElement()
上使用pXMLUsers
,但它说IXMLDOMNodeListPtr has no member appendChild
。
我不知道如何创建新元素。
感谢。
答案 0 :(得分:1)
您不能使用IXMLDOMNodeListPtr
附加孩子 - 它只是为了迭代现有的孩子。
您可以直接使用IXMLDOMElementPtr
致电pXMLDocElement->appendChild()
在您的文档中添加子元素。
答案 1 :(得分:1)
好的,我找到了一个解决方案,感谢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);