Rebse
Rebse

Reputation: 10377

Groovy xmlparser get attribute value

I have a problem to parse an attribute value from following XML:

s='''<?xml version="1.0" encoding="UTF-8"?>
<web-ext
  xmlns="http://websphere.ibm.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://websphere.ibm.com/xml/ns/javaee http://websphere.ibm.com/xml/ns/javaee/ibm-web-ext_1_0.xsd"
  version="1.0">
  <reload-interval value="3"/>
  <context-root uri="foo/bar" />
  <enable-directory-browsing value="false"/>
  <enable-file-serving value="true"/>
  <enable-reloading value="true"/>
  <enable-serving-servlets-by-class-name value="false" />
</web-ext>
'''

def contextroot
def xml = new XmlParser(false,false).parseText(s)
xml.each {
 if (it.name() == "context-root")
 contextroot = it.attributes().uri
}

It gives me the correct value. But is there a more direct approach? Something like

xml.name("context-root").uri

doesn't work.

Upvotes: 3

Views: 5868

Answers (1)

Szymon Stepniak
Szymon Stepniak

Reputation: 42184

If you want to access this attribute directly you can do it with

xml.'context-root'[0].@uri

Upvotes: 8

Related Questions