例子:
<fruit name="mango"/>
我想得到如下输出:
name="mango"
最佳答案
您可以使用attributes
方法将某些Node
的属性提取为散列。
Returns a hash containing the node’s attributes. The key is the attribute name, the value is a Nokogiri::XML::Attr representing the attribute.
Read this也是。
我给你举个例子。这是一个 XML 文档:
<?xml version="1.0" encoding="utf-8" ?>
<files>
<file exists="true">
<content />
</file>
<file exists="false">
<content />
</file>
</files>
以及处理它的 Ruby 代码:
require "nokogiri"
doc = Nokogiri::XML(File.read "my.xml")
doc.css("files file[exists]").first.attributes
# => #<Nokogiri::XML::Attr:0x1184470 name="exists" value="true">
doc.css("files file[exists]").first.attributes["exists"].value
# => "true"
关于ruby - 如何使用 Nokogiri 从 xml 中提取属性名称和值对?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3390209/