简体   繁体   中英

Ruby Nokogiri xml parsing

给定以下节点,我想搜索值“ H90.5”并返回属性字符串dx1

<fld-21 dx-version="ICD10" dx1="H90.5" dx2="I25.9" dx3="I25.3" dx4="" dx5="" dx6="" dx7="" dx8="" dx9="" dx10="" dx11="" dx12=""/>

这是搜索属性的xpath技巧:

doc.at('//@*[.="H90.5"]').name

Given:

frag = Nokogiri::XML.fragment('<fld-21 dx-version="ICD10" dx1="H90.5" dx2="I25.9" dx3="I25.3" dx4="" dx5="" dx6="" dx7="" dx8="" dx9="" dx10="" dx11="" dx12=""/>')

If you have multiple elements and multiple possible attributes you could do:

frag.css('fld-21').map do |node|
  node.attributes.select do |key, attr|
     key =~ /dx\d+/ && attr.value == "H90.5"
  end.keys
end

It returns:

[["dx1"]]

Otherwise you can use .at instead of .css and .detect instead .select .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM