2012-11-22 64 views
1

我正在嘗試使用pugixml從大型XML文件中提取數據。我只是感興趣的值的節點BAR和值Nm:如何使用pugixml提取子數據?

<Document xmlns="xxxxxx" xmlns:xsi="vvvvvvv"> 
     <Outer> 
     <HDR> 
      <MsgId>FOOBAR222222</MsgId> 
      <ID> 
      <AAAAA>FOOBAR222222</AAAAA> 
      </ID> 
     </HDR> 
     <ENTRY> 
      <Status>existing</Status> 
      <ELEM> 
      <TM>2012-11-19T13:00:00</TM> 
      </ELEM> 
      <FOO> 
      <BAR>xxxxx</BAR> 
      <NM> 
       <Nm>yyyyyyy</Nm> 
      </NM> 
      </FOO> 
     </ENTRY> 

從我所看到的,有可能走的根文件,但是,我得到的訪問家長和孩子有點失落節點:

 void walk(xml_node parent) 
     { 
      for(xml_node child = parent.first_child(); child; child = child.next_sibling()) 
      { 
       // ... Would like to output: "FOO: xxxx/NM: yyyyyyyy" 
      } 
     } 
+0

另一個有用的鏈接是:http://pugixml.googlecode.com/svn/tags /latest/docs/samples/traverse_iter.cpp – poseid

回答

2

你可以給參數到first_child()和其他成員函數:

auto Outer = document.first_child("OUTER"); 
auto Entry = Outer.first_child("ENTRY"); 
auto Foo = Entry.first_child("FOO"); 

當您終於到達目的地時,使用.value()來獲取節點值。

PugiXML還具有XPath支持,但在那種情況下可能會過度殺傷。

+0

謝謝!如果ENTRY重複多次,那麼first_child選擇工作呢?我需要遍歷所有ENTRY ...在我的問題中不清楚,對不起! – poseid

+0

然後用'Foo = Foo.next_sibling(「FOO」)'來到下一個Foo節點:) –

+0

太好了!現在,我明白了...只是一個額外的問題,試圖爲first_child提供一個參數給出:沒有匹配的函數調用'pugi :: xml_node :: first_child(const char [9])' – poseid

0

Pugi也有一個簡單的路徑設施5.10. Miscellaneous functions

你可以做上面只有一行:

document.first_element_by_path("/Document/Outer/ENTRY/FOO/BAR").first_child().value();