简体   繁体   中英

Parsing XML with REXML

I have this XML document and I want to find an specific GitHubCommiter using REXML. Hoy do I do that?

<users>
 <GitHubCommiter id="Nerian">
  <username>name</username>
  <password>12345</password>
 </GitHubCommiter>

 <GitHubCommiter id="xmawet">
  <username>name</username>
  <password>12345</password>
 </GitHubCommiter>

 <GitHubCommiter id="JulienChristophe">
  <username>name</username>
  <password>12345</password>
  </GitHubCommiter>
</users>

I have tried:

log = REXML::Document.new(file)                                                      
root = log.root                                                                         username = root.elements["GitHubCommiter['#{github_user_name}']"].elements['username'].text      
password =     root.elements["GitHubCommiter['#{github_user_name}']"].elements['password'].text
root.elements["GitHubCommiter['id'=>'#{github_user_name}']"].text

But I don't find a way to do it. Any idea?

The docs say for elements (emphasis mine):

[]( index, name=nil) Fetches a child element. Filters only Element children, regardless of the XPath match.

index: the search parameter. This is either an Integer, which will be used to find the index'th child Element, or an XPath, which will be used to search for the Element.

So it needs to be XPath:

root.elements["./GitHubCommiter[@id = '{github_user_name}']"]

etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM