How to retrieve the nokogiri processing instructio

2019-07-15 08:34发布

I am parsing the XML using Nokogiri.

I am able to retrieve the stylesheets. But not the attributes of each stylesheet.

1.9.2p320 :112 >style = xml.xpath('//processing-instruction("xml-stylesheet")').first
=> #<Nokogiri::XML::ProcessingInstruction:0x5459b2e name="xml-stylesheet">
style.name
=> "xml-stylesheet"
style.content
=> "type=\"text/xsl\" href=\"CDA.xsl\""

Is there any easy way to get the type, href attributes values?

OR

Only way is to parse the content(style.content) of the processing instruction ?

2条回答
够拽才男人
2楼-- · 2019-07-15 09:18

I solved this problem by following instruction in below answer.

Can Nokogiri search for "?xml-stylesheet" tags?

Added new to_element method to Nokogiri::XML::ProcessingInstruction class

 class Nokogiri::XML::ProcessingInstruction
   def to_element
     document.parse("<#{name} #{content}/>")
   end
 end

 style = xml.xpath('//processing-instruction("xml-stylesheet")').first
 element = style.to_element

To retrieve the href attribute value

 element.attribute('href').value
查看更多
Juvenile、少年°
3楼-- · 2019-07-15 09:20

Cannot you do that?

style.content.attribute['type'] # or attr['type'] I am not sure
style.content.attribute['href'] # or attr['href'] I am not sure

Check this question How to access attributes using Nokogiri .

查看更多
登录 后发表回答