fossmaniac
fossmaniac

Reputation: 11

How to extract attribute name and value pair from xml using Nokogiri?

Example:

<fruit name="mango"/>

I want to get output as:

name="mango"

Upvotes: 1

Views: 3037

Answers (4)

G. Allen Morris III
G. Allen Morris III

Reputation: 1042

Some code that ouputs "name="mango" from xml input "<frunit 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

Upvotes: 0

opensource
opensource

Reputation: 748

def getattributestest(doc,attr,rexg)
  arr = doc.css(rexg)
  cnode = arr.select {|node|  node}
  cnode.inject([]) do |rs,i|
    rs << i.attributes[attr]
  end

Upvotes: 0

Todd Yandell
Todd Yandell

Reputation: 14696

xml   = %(<fruit name="mango"/>)
fruit = Nokogiri.XML(xml) % "fruit"

fruit.attributes.values.map(&:to_xml).join.strip

Upvotes: 2

Daniel O&#39;Hara
Daniel O&#39;Hara

Reputation: 13438

You can use the attributes method to extract attributes of some Node as a hash.

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 too.

I will show you an example. Here is an XML document:

<?xml version="1.0" encoding="utf-8" ?>
<files>
    <file exists="true">
        <content />
    </file>
    <file exists="false">
        <content />
    </file>
</files>

And Ruby code to process it:

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"

Upvotes: 3

Related Questions