【问题标题】:How to extract attribute name and value pair from xml using Nokogiri?如何使用 Nokogiri 从 xml 中提取属性名称和值对?
【发布时间】:2015-09-08 09:45:29
【问题描述】:

例子:

<fruit name="mango"/>

我想得到如下输出:

name="mango"

【问题讨论】:

    标签: ruby nokogiri


    【解决方案1】:

    您可以使用attributes 方法提取一些Node 的属性作为哈希。

    返回包含节点属性的哈希。键是属性名,值是表示属性的 Nokogiri::XML::Attr。

    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"
    

    【讨论】:

    • 先生,我读了这个,但无法解决,请举个小例子!!
    • 我在答案中添加了一个示例。
    【解决方案2】:
    xml   = %(<fruit name="mango"/>)
    fruit = Nokogiri.XML(xml) % "fruit"
    
    fruit.attributes.values.map(&:to_xml).join.strip
    

    【讨论】:

      【解决方案3】:
      def getattributestest(doc,attr,rexg)
        arr = doc.css(rexg)
        cnode = arr.select {|node|  node}
        cnode.inject([]) do |rs,i|
          rs << i.attributes[attr]
        end
      

      【讨论】:

        【解决方案4】:

        从 xml 输入“”输出“name="mango" 的一些代码

        require 'nokogiri'
        doc = Nokogiri::XML %q|<xml><fruit name="mango"/></xml>|
        element = doc.xpath("//fruit")
        hash =  Hash[doc.xpath("//fruit")[0].attributes.map{ |n, v| [ n, v.value ]}]
        hash.each do |k, v|
          puts  %Q|#{k}="#{v}"|
        end
        

        【讨论】:

          猜你喜欢
          • 2014-07-21
          • 2020-12-22
          • 1970-01-01
          • 2013-02-24
          • 1970-01-01
          • 2016-05-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多