質問

I am parsing a piece of XML using XmlSlurper and need to find an xml elements value. The challenge in this is that i am not always sure if the casing in the xml document will be correct, so i need to find the element in any possible way.

Example:

<start>
   <Header>
      <Elem>1234</Elem>
   </Header>
</start>

Getting the value of Elem will be:

def parsedXml = new XmlSlurper().parseText(xml)
parsedXml.Header.Elem

but i also need to find it when the casing is different.. so is there a way in which i can express to find the value of Elem when the casing is different?

<start>
   <header>
      <elem>1234</elem>
   </header>
</start>

def parsedXml = new XmlSlurper().parseText(xml)
parsedXml.header.elem
役に立ちましたか?

解決

There probably is a much better solution (e.g. it seems that using XPath it should be possible to compare node names case insensitively), but converting the document to lowercase will work. If you care about the casing of the text nodes inside the document, you may only convert to lowercase the tag elements:

def toLowerCaseXmlTags(xmlText) {
    xmlText.replaceAll(/<[^<>]+>/) { it.toLowerCase() }
}

text = """
<start>
   <Header>
      <Elem>1234</Elem>
      <SomeText>This should PRESERVE casing</SomeText>
   </Header>
</start>
"""

def xml = new XmlSlurper().parseText(toLowerCaseXmlTags(text))
assert xml.header.elem.text() == '1234'
assert xml.header.sometext.text() == 'This should PRESERVE casing'

Quick and dirty, but it works :P

他のヒント

XML is case sensitive and so is the property lookup of XmlSlurper results. You will need to use the GPathResult.find() method:

def header = parsedXml.find { it.name().toLowerCase() == 'header' }
def elem = header.find { it.name().toLowerCase() == 'elem' }

Check out the groovy documentation for more ways you can use XmlSlurped documents.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top