2013-01-16 38 views
0

我是XML的初學者。我正在使用libxml。我創建了一個XML文件像這樣:正在檢索一個元素

<example> 

    <Path Name="one">Properties/one</Path> 
    <Path Name="two">Properties/two</Path> 
    <Path Name="three">Properties/three</Path> 
    <Path Name="four">Properties/four</Path> 

</example> 

我的問題是如何能得到例如屬性/一個一個這是路徑的名稱。 ?

謝謝。

+1

是獲取文本或文本得到一個子問題? –

+0

問題是提取文本 – tchike

+0

你可以編輯你的問題,包括你的C++代碼,顯示你迄今爲止做了什麼? –

回答

1

快速和骯髒的,你可以做這樣的:

std::string strRetVal; 
xmlDocPtr pXMLDoc = xmlParseFile("filename.xml"); // read the xml file 
xmlNodePtr rootNode = xmlDocGetRootElement(pXMLDoc); // get the root node (<example>) 
xmlNodePtr pNode = rootNode->children; 
while (pNode) 
{ // walk through all children nodes 
    if (pNode->type == XML_ELEMENT_NODE) 
    { 
     std::string strElemName((char *)pNode->name)); // find all <Path> elements 
     if (strElemName == "Path") 
     { 
      xmlAttrPtr pAttr = m_pXMLNode->properties; 
      while (pAttr) 
      { // walk through all the attributes and find the required one 
       if (pAttr->type == XML_ATTRIBUTE_NODE) 
       { 
        str::string strAttrName((char *)pAttr->name); 
        str::string strAttrVal((char *)pAttr->children->content); 
        if ((strAttrName == "Name") && (strAttrVal == "one")) break; // found 
       } 
       pAttr = pAttr->next; 
      } 
     } 
    } 
    pNode = pNode->next; 
} 
if (pNode) 
{ // pNode is the element with an attribute "Name" of value "one" 
    strRetVal = (char*)xmlNodeGetContent(pNode); // get its content (/Properties/one) 
}