【问题标题】:how can I get some attributes when using Nokogiri使用 Nokogiri 时如何获取一些属性
【发布时间】:2021-08-08 10:32:12
【问题描述】:

这是我的xml字符串,我想得到英文结果“B”

  <body>
    <attributes>
      <attr name="Math" namespace="">A</attr>
      <attr name="English" namespace="" parentName="">B</attr>
    </attributes>
  </body>

这是我解析 xml 字符串的方式

result = Nokogiri::XML(xml)
res = Hash.from_xml(result.to_s)

但是当我使用res["body"]["attributes"]时,我只能得到结果集

=> {"attr"=>["A", "B"]}

因为attr的顺序不规则, 那么如何判断英文结果到底是什么? 谢谢!

【问题讨论】:

    标签: ruby xml-parsing nokogiri


    【解决方案1】:

    你可以使用css选择器:

    result.css("attr[name='English']").children.to_s
    

    会给你"B"

    【讨论】:

    • 谢谢!这行得通!现在如何获取英文的命名空间,如果有办法迭代 attr ?
    • result.css("attr[name='English']") 将返回您可以从中迭代的集合。 english = result.css("attr[name='English']"); english.first.attributes["namespace"].value # ""
    猜你喜欢
    • 2012-07-21
    • 2015-12-29
    • 1970-01-01
    • 2013-02-24
    • 2012-01-08
    • 2011-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多