Retrieving elements in accordance with REXML XPath

I would like to go through all the elements <HeadA>and <HeadB>in the XML file and add to it a unique identifier. The approach I've tried so far:

@xml.each_element('//HeadA | //HeadB') do |heading|
  #add a new id
end

The problem is that the node set from XPath //HeadA | //HeadBis everything HeadAfollowed by all HeadBs. I need an ordered list of everyone HeadAand HeadBin the order in which they appear in the document.

To clarify, my XML might look like this:

<Doc>
  <HeadA>First HeadA</HeadA>
  <HeadB>First HeadB</HeadB>
  <HeadA>Second HeadA</HeadA>
  <HeadB>Second HeadB</HeadB>
</Doc>

And what I get from XPath:

  <HeadA>First HeadA</HeadA>
  <HeadA>Second HeadA</HeadA>
  <HeadB>First HeadB</HeadB>
  <HeadB>Second HeadB</HeadB>

when i need to get the nodes in order:

  <HeadA>First HeadA</HeadA>
  <HeadB>First HeadB</HeadB>
  <HeadA>Second HeadA</HeadA>
  <HeadB>Second HeadB</HeadB>

so I can add identifiers sequentially.

+3
source share
4 answers

, , , : P

@xml.each_element('//*[self::HeadA or self::HeadB]') do |heading|
  puts heading.text
end
+1

Nokogiri XML:

xml = %q{
<Doc>
    <HeadA>First HeadA</HeadA>
    <HeadB>First HeadB</HeadB>
    <HeadA>Second HeadA</HeadA>
    <HeadB>Second HeadB</HeadB>
</Doc>
}

doc = Nokogiri::XML(xml)
doc.search('//HeadA | //HeadB').map{ |n| n.inner_text } #=> ["First HeadA", "First HeadB", "Second HeadA", "Second HeadB"]

map each each_with_index . , .

+1

, HeadA HeadA HeadB?

@xml.each_element("//HeadA") do |headA|
  #do stuff to headA
  headA.each_element("HeadB") do |headB|
    #do stuff to headB
  end
end
0

:

as_string = @xml.to_s
counter = 0
as_string.gsub!(/(<HeadA>|<HeadB>)/) do |str|
  result = str.sub '>', " id='#{counter}'>"
  counter += 1
  result
end
@xml = REXML::Document.new as_string

, , , .

: D-D-Doug, :

counter = 0
@xml.each_element('//[self::HeadA or self::HeadB]') do |heading|
  heading.attributes['id'] = "id%03d" % counter
  counter += 1
end

.

0

Source: https://habr.com/ru/post/1774954/


All Articles