2012-07-12 54 views
1

迭代元素我有類似這樣的XML文件:訪問XML子與Ruby和引入nokogiri

<Companies type="Container"> 
<Company type="Category"> 
    <Name type="Property">Company 123</Name> 
    <Location type="Property">New York</Location> 
    <Employees type="Container"> 
     <Employee type="Reference"> 
      <Name type="Property">John Smith</Name> 
      <Email type="Property">[email protected]</Email> 
     </Employee> 
     <Employee type="Reference"> 
      <Name type="Property">Jane Doe</Name> 
      <Email type="Property">[email protected]</Email> 
     </Employee> 
</Company> 
<Company type="Category"> 
    <Name type="Property">Company ABC</Name> 
    <Location type="Property">Minneapolis</Location> 
    <Employees type="Container"> 
     <Employee type="Reference"> 
      <Name type="Property">John Doe</Name> 
      <Email type="Property">[email protected]</Email> 
     </Employee> 
     <Employee type="Reference"> 
      <Name type="Property">Jane Smith</Name> 
      <Email type="Property">[email protected]</Email> 
     </Employee> 
</Company> 

我要通過這個文件來走,並讓所有的信息出來,所以我可以工作它。我可以使用Nokogiri循環訪問每個「公司」並獲得「名稱」和「位置」屬性。然而,我不知道該怎麼做,是爲每個「公司」獲取「員工」信息。

我敢肯定我錯過了一些簡單的事情,但我一直在挖掘內部撬,我似乎無法揭開神祕面紗。大大幫助讚賞。

+0

請發佈您的代碼獲取名稱和位置。由於Nokogiri有很多方法可以做,所以我可以嘗試根據您選擇使用的方法來定製我的答案。 – Kelvin 2012-07-12 17:51:20

+0

也請修復你的xml。名稱類型缺少關閉引號,缺少「Employee」和「Companies」結束標記。 Nokogiri的默認分析模式不會抱怨,但您會收到錯誤的數據。 – Kelvin 2012-07-12 17:59:43

回答

8

注:我強烈建議在開發時通過參數(raw_xml_string, nil, nil, Nokogiri::XML::ParseOptions::STRICT)來捕捉格式不正確的xml。

xdoc = Nokogiri.XML(raw_xml_string) 

(xdoc/'/Companies/Company').each {|com| 
    puts "company:" 
    p [(com/'./Name').text, (com/'./Location').text] 

    puts "employees:" 
    # you need another loop to grab the employees. 
    (com/'Employees/Employee').each {|emp| 
    p [(emp/'./Name').text, (emp/'./Email').text] 
    } 
} 

一兩件事,當你使用/%方法需要注意的是,他們會選擇任何後裔,而不僅僅是直接孩子。這就是爲什麼我用'./Name'而不僅僅是'Name'

+0

工作。非常感謝! – n8gard 2012-07-13 02:08:07

1

您的XML格式錯誤。

Nokogiri可以幫助您找出問題出在哪裏,使用errors()方法。解析XML和檢查errors()

doc = Nokogiri::XML(xml) 
puts doc.errors 

輸出:

Unescaped '<' not allowed in attributes values 
attributes construct error 
Couldn't find end of Start Tag Name line 4 
Opening and ending tag mismatch: Company line 3 and Name 
Opening and ending tag mismatch: Employees line 6 and Company 
Unescaped '<' not allowed in attributes values 
attributes construct error 
Couldn't find end of Start Tag Name line 17 
Opening and ending tag mismatch: Company line 16 and Name 
Opening and ending tag mismatch: Employees line 19 and Company 

引入nokogiri會嘗試修復了XML,但有些事情不能做正確。修復缺失的引號就是其中之一:

<Name type="Property>Company 123</Name> 
<Name type="Property>Company ABC</Name> 

是錯誤的。他們應該是:

<Name type="Property">Company 123</Name> 
<Name type="Property">Company ABC</Name> 

而且,</Employees>結束標記在這兩種情況下丟失,但引入nokogiri會修復這些。

+0

+1代表'errors()' – Kelvin 2012-07-13 16:09:52