How to retrieve the nokogiri processing instruction attributes?

六眼飞鱼酱① 提交于 2019-12-13 15:59:35

问题


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 ?


回答1:


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



回答2:


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 .



来源:https://stackoverflow.com/questions/13066231/how-to-retrieve-the-nokogiri-processing-instruction-attributes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!