tags:

views:

99

answers:

3

Example:

<fruit name="mango"/>

I want to get output as:

name="mango"
A: 

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"
floatless
sir I read this but not able to work it out please give a small example!!
fossmaniac
I've added an example to my answer.
floatless
A: 
xml   = %(<fruit name="mango"/>)
fruit = Nokogiri.XML(xml) % "fruit"

fruit.attributes.values.map(&:to_xml).join.strip
Todd Yandell
A: 
def getattributestest(doc,attr,rexg)
  arr = doc.css(rexg)
  cnode = arr.select {|node|  node}
  cnode.inject([]) do |rs,i|
    rs << i.attributes[attr]
  end
田晓波