如何使用带有 REXML 的 Ruby 获取 XML 标记的属性? [英] How to get the attributes of an XML tag using Ruby with REXML?

查看:38
本文介绍了如何使用带有 REXML 的 Ruby 获取 XML 标记的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想仅在 Ruby 中使用 REXML 以特定方式输出 xml 文件.这是 xml 文件的样子:

I want to output an xml file in a specific way only using REXML with Ruby. Here is what the xml file looks like:

<desc>
     <id>2408</id>
     <who name="Joe Silva">joe@silva.com</who>
     <when>Today</when>
     <thetext>Hello World</thetext>
</desc>
<desc>
     <id>2409</id>
     <who name="Joe Silva2">joe2@silva.com</who>
     <when>Future</when>
     <thetext>Hello World Again</thetext>
</desc>

到目前为止,这是我使用的代码:

So far, here is the code I use:

document.elements.each("//desc") {
    |e| e.elements.each 
        |i| puts "#{i.name} : #{i.text}"
    puts "\n"
}

这给了我以下输出:

commentid : 2408
who : joe@silva.com
bug_when : Today
thetext : Hello World

commentid : 2409
who : joe2@silva.com
bug_when : Future
thetext : Hello World Again

我可以访问每个标签的文本,但不能访问它们的属性.如何访问属性并获得带有 name 属性的输出?

I can access each tag's text but not their attributes. How do I get access to the attributes and get an output with the name attribute?

所以我想要的输出是:

commentid : 2408
name : Joe Silva
who : joe@silva.com
bug_when : Today
thetext : Hello World

如果需要进一步解释,请告诉我.

Let me know if further explanation is required.

推荐答案

我不会使用 REXML,而是会使用 Nokogiri.使用它,我会写一些类似的东西:

I wouldn't use REXML, but instead would use Nokogiri. Using that, I'd write something like:

require 'nokogiri'

doc = Nokogiri::XML(<<EOT)
<xml>
<desc>
     <id>2408</id>
     <who name="Joe Silva">joe@silva.com</who>
     <when>Today</when>
     <thetext>Hello World</thetext>
</desc>
<desc>
     <id>2409</id>
     <who name="Joe Silva2">joe2@silva.com</who>
     <when>Future</when>
     <thetext>Hello World Again</thetext>
</desc>
</xml>
EOT

data = doc.search('desc').map{ |desc|
  desc.children.reject(&:text?).map { |desc_child|
    [desc_child.name, desc_child.text]
  }.to_h
}

data
# => [{"id"=>"2408",
#      "who"=>"joe@silva.com",
#      "when"=>"Today",
#      "thetext"=>"Hello World"},
#     {"id"=>"2409",
#      "who"=>"joe2@silva.com",
#      "when"=>"Future",
#      "thetext"=>"Hello World Again"}]

它提供了一个包含节点名称及其文本的哈希数组.

That provides an array of hashes containing the node names and their text.

如何更改要用作键的节点的名称并将其打印出来由您自己解决.

How to change the name of the nodes to be used as keys and print it out is left for you to figure out.

这篇关于如何使用带有 REXML 的 Ruby 获取 XML 标记的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆