Groovy xmlparser 获取属性值

Reb*_*bse 2 groovy

我在解析以下 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
}
Run Code Online (Sandbox Code Playgroud)

它给了我正确的价值。但是有没有更直接的方法呢?就像是

xml.name("context-root").uri
Run Code Online (Sandbox Code Playgroud)

不起作用。

Szy*_*iak 6

如果你想直接访问这个属性,你可以用

xml.'context-root'[0].@uri
Run Code Online (Sandbox Code Playgroud)

  • 或者确实是`xml.'context-root'.@uri[0]` (3认同)