0

I wrote this code, which should be self explaining:

def parse_kapitel(node)
  if node.node_name.eql? 'nummer'
    tmp_kapitel = Kapitel.new
    puts node.next_element['V']
    puts node.next_element.next_element['V']
    puts node.next_element.next_element.next_element['V']    
  end
end

My xml:

<kapitel>
      <nummer V="1"/>
      <von_icd_code V="A00"/>
      <bis_icd_code V="B99"/>
      <bezeichnung V="Bestimmte infektiöse und parasitäre Krankheiten"/>
      <gruppen_liste>
        <gruppe>
          <von_icd_code V="A00"/>
          <bis_icd_code V="A09"/>
          <bezeichnung V="Infektiöse Darmkrankheiten"/>
          <diagnosen_liste>
            <diagnose>

You can see my code is very tedious because I use next_element several times.

How can I write the whole thing shorter?

2
  • Do you want a list of diagnoses per ICD chapter/group?
    – Matt
    Sep 9, 2013 at 12:37
  • Your XML example isn't valid. Please use valid examples when asking questions. Sep 9, 2013 at 16:48

1 Answer 1

1

How is this?

require 'nokogiri'

doc = Nokogiri.XML <<-eol
<kapitel>
      <nummer V="1"/>
      <von_icd_code V="A00"/>
      <bis_icd_code V="B99"/>
      <bezeichnung V="Bestimmte infektiöse und parasitäre Krankheiten"/>
      <gruppen_liste>
        <gruppe>
          <von_icd_code V="A00"/>
          <bis_icd_code V="A09"/>
          <bezeichnung V="Infektiöse Darmkrankheiten"/>
</kapitel
            eol

doc.xpath("/kapitel//@V").map(&:text)
# => ["1",
#     "A00",
#     "B99",
#     "Bestimmte infektiöse und parasitäre Krankheiten",
#     "A00",
#     "A09",
#     "Infektiöse Darmkrankheiten"]

If you want the first three sibling's values of attribute V,then do something like this:

doc.xpath("/kapitel/*[name(.)='nummer']/following-sibling::*")[0..2].map{|n|n["V"]}
# => ["A00", "B99", "Bestimmte infektiöse und parasitäre Krankheiten"]
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.