2011-07-10 58 views
1

我有一個users.xml中如何使用msxml解析器創建子元素?

<?xml version="1.0"?> 
<Data> 
    <Users> 
     <User name="xyz" email="[email protected]"> 
        <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; 

如何創建一個子元素用戶用戶用戶元素元素。

我已經pXMLUsers使用createElement()試過,但它說IXMLDOMNodeListPtr has no member appendChild

我不知道如何創建一個新的元素。

謝謝。

回答

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); 
1

您不能使用IXMLDOMNodeListPtr追加子 - 它只是迭代現有的兒童。

可以使用IXMLDOMElementPtr直接調用pXMLDocElement->appendChild()在文檔中添加子元素。

+0

感謝您的建議。你可以建議我怎麼能得到IXMLDOMElementPtr參考''元素 – Searock

+0

使用XPath找到元素 - 這裏的XPath樣品字符串:http://msdn.microsoft.com/en-us/library/ms256086.aspx,COM API info(IXMLDOMSelection)here:http://msdn.microsoft.com/en-us/library/ms759171(v=VS.85).aspx –