【问题标题】:How to retrieve the nokogiri processing instruction attributes?如何检索 nokogiri 处理指令属性?
【发布时间】:2012-10-15 11:56:26
【问题描述】:

我正在使用 Nokogiri 解析 XML。

我能够检索样式表。但不是每个样式表的属性。

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\""

有什么简单的方法可以获取type、href属性值吗?

唯一的办法就是解析处理指令的内容(style.content)?

【问题讨论】:

  • 如果您包含一个您尝试解析的 XML 的简短示例,将会有所帮助。

标签: ruby xml nokogiri


【解决方案1】:

我按照以下答案中的说明解决了这个问题。

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

向 Nokogiri::XML::ProcessingInstruction 类添加新的 to_element 方法

 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

检索 href 属性值

 element.attribute('href').value

【讨论】:

    【解决方案2】:

    你不能这样做吗?

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

    检查这个问题How to access attributes using Nokogiri

    【讨论】:

    • 这给了我未定义的方法属性或字符串错误的属性。
    猜你喜欢
    • 1970-01-01
    • 2013-06-11
    • 2013-11-26
    • 1970-01-01
    • 1970-01-01
    • 2017-11-07
    • 2012-12-02
    • 1970-01-01
    • 2021-05-25
    相关资源
    最近更新 更多