2011-05-24 59 views
2

嗨 我想使用XML文件作爲配置文件,從中我將讀取我的應用程序的參數。我遇到過PugiXML庫,但是我有問題獲取屬性的值。 我的XML文件看起來像Parsin XML文件使用pugixml

<?xml version="1.0"?> 
<settings> 
    <deltaDistance> </deltaDistance> 
    <deltaConvergence>0.25 </deltaConvergence> 
    <deltaMerging>1.0 </deltaMerging> 
    <m> 2</m> 
    <multiplicativeFactor>0.7 </multiplicativeFactor> 
    <rhoGood> 0.7 </rhoGood> 
    <rhoMin>0.3 </rhoMin> 
    <rhoSelect>0.6 </rhoSelect> 
    <stuckProbability>0.2 </stuckProbability> 
    <zoneOfInfluenceMin>2.25 </zoneOfInfluenceMin> 
</settings> 

削我使用此代碼

void ReadConfig(char* file) 
{ 
    pugi::xml_document doc; 
    if (!doc.load_file(file)) return false; 

    pugi::xml_node tools = doc.child("settings"); 

    //[code_traverse_iter 
    for (pugi::xml_node_iterator it = tools.begin(); it != tools.end(); ++it) 
    { 
     cout<<it->name() << " " << it->attribute(it->name()).as_double(); 
    } 

} 

,我也試圖用這種

void ReadConfig(char* file) 
{ 
    pugi::xml_document doc; 
    if (!doc.load_file(file)) return false; 

    pugi::xml_node tools = doc.child("settings"); 

    //[code_traverse_iter 
    for (pugi::xml_node_iterator it = tools.begin(); it != tools.end(); ++it) 
    { 
     cout<<it->name() << " " << it->value(); 
    } 

} 

屬性被corectly加載XML文件,但是所有的值都等於0.有人能告訴我我做錯了什麼嗎?

+0

歡迎來到SO。要正確地使用XML格式,只要確保它至少縮進了4個空格(或者使用編輯器中的「{}」按鈕) – 2011-05-24 17:02:50

回答

6

我認爲你的問題是你期望值存儲在節點本身,但它確實在一個CHILD文本節點。文檔的快速掃描顯示,你可能需要的

it->child_value() 

代替

it->value() 
1

你想獲得一個給定節點的所有屬性,或者你想通過名稱的屬性?

對於第一種情況,你應該能夠使用這個代碼:

unsigned int numAttributes = node.attributes(); 
for (unsigned int nAttribute = 0; nAttribute < numAtributes; ++nAttribute) 
{ 
    pug::xml_attribute attrib = node.attribute(nAttribute); 
    if (!attrib.empty()) 
    { 
     // process here 
    } 
} 

對於第二種情況:

LPCTSTR GetAttribute(pug::xml_node & node, LPCTSTR szAttribName) 
{ 
    if (szAttribName == NULL) 
     return NULL; 

    pug::xml_attribute attrib = node.attribute(szAttribName); 
    if (attrib.empty()) 
     return NULL; // or empty string 

    return attrib.value(); 
} 
1

如果你想股票的純文本數據轉換成像

節點
<name> My Name</name> 

你需要使它像

rootNode.append_child("name").append_child(node_pcdata).set_value("My name"); 

如果你想存儲數據類型,你需要設置一個屬性。我認爲你想要的是能夠直接讀取值的權利?

當你正在寫的節點,

rootNode.append_child("version").append_attribute("value").set_value(0.11) 

當你想讀它,

rootNode.child("version").attribute("version").as_double() 

至少這是我做這件事的方式!