Announcement Announcement Module
Collapse
No announcement yet.
more help with parsing xml string Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • more help with parsing xml string

    hello all,
    I have another question about parsing an xml string. bellow is the xml string i am working with:

    HTML Code:
    alum_string= ""<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <person>
      <id>jIi-hRi4cI</id>
      <first-name>Jason</first-name>
      <last-name>Wucinski</last-name>
      <languages total="2">
        <language>
          <language>
            <name>English</name>
          </language>
          <proficiency>
            <level>native_or_bilingual</level>
          </proficiency>
        </language>
        <language>
          <language>
            <name>Setswana</name>
          </language>
          <proficiency>
            <level>elementary</level>
          </proficiency>
        </language>
      </languages>
    </person>
    ""
    I was able to parse single nodes, such as first-name and last-name this way:
    Code:
    def alum = new XmlSlurper().parseText(alum_string)
    print  " first name: ${alum.'first-name'} \n"
    print  " last name:  ${alum.'last-name'} \n"
    //output:
    // first name: Jason
    //last name: wucinski
    but when i try to parse a node that repeats (such as language proficiency) the strings end up being grouped together and cant be separated. below is the code i use to do parse languages:
    Code:
    print("languages: ")
    alum.languages.each{languages ->
         print("${alum.languages.language.language.name}  \n")
    //output:
    //languages: EnglishSetswana  
    //languages: EnglishSetswana 
    }
    the output iterates twice, which is good i guess since there are two languages in the above xml, but the two language names are grouped together. I would expect the output to be:

    languages: English
    languages: Setswana

    what's going on? can anyone help? thanks in advance
    jason

  • #2
    well, not a lot of help here it seems. if anyone else comes a cross a similar problem, i figured this out:

    Code:
    def i = 0	
    alum.languages.language.each{name ->
    languageName ="${alum.languages.language.'language'[i]}.text()"
    languageSkill=	"${alum.languages.language.'proficiency'[i]}.text()"
    	i ++
    	}
    notice the [i]. it seems you can iterate through repeated nodes with this

    Comment


    • #3
      When you iterate over a set of elements, you don't need to keep querying from the document root. So your code can be:

      Code:
      for (lang in alum.languages.language) {
          languageName = lang.language.text()
          languageSkill = lang.proficiency.text()
      }
      Note that it's preferable in Groovy to use a 'for' loop rather than the each() method.

      Comment

      Working...
      X