ruby - 如何使用 Nokogiri 从 xml 中提取属性名称和值对?

标签 ruby nokogiri

例子:

<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/

相关文章:

ruby-on-rails - 来自 Ruby on Rails 应用程序的 FTPS (TLS/SSL)

Java 客户端/Ruby 服务器套接字连接

ruby - 使用 Nokogiri 创建带有命名空间的 XML 元素

ruby - XPath 使用 Nokogiri 返回空数组

ruby - 单击 Ruby Mechanize 中 .each 循环内的链接

ruby - 无法捕获 Ruby 中的异常

php - 从 PHP 切换到 Ruby - 这是性能的答案吗?

ruby-on-rails - 从 ruby 字符串中解析印度货币

css - 如何使用 Nokogiri 获取列表中的第二张图片?

ruby-on-rails - Nokogiri 无法在 CentOS 中读取/解析 HTML 文件的结构