开发者

nicer way of handling dom than DOMCategory?

开发者 https://www.devze.com 2023-01-01 07:17 出处:网络
I\'m trying to create a D开发者_如何学GoSL that can easily use a dom node. Using DOMCategory is nice, but adds the noise of \'use(DOMCategory)\'. Is there a way to avoid that?

I'm trying to create a D开发者_如何学GoSL that can easily use a dom node. Using DOMCategory is nice, but adds the noise of 'use(DOMCategory)'. Is there a way to avoid that?

I tried wrapping the script call inside a call to 'use', but this doesn't seem to work in closures.


You can use groovy's runtime mixin feature to permanently mix in the category. Class.mixin adds the applicable methods in the category to the class's metaClass. Apply it to the classes and interfaces that appear as the first parameter to each category method, and the category will be available without enclosing the code in a use(DOMCategory) block.

Example:

import org.w3c.dom.*
import groovy.xml.DOMBuilder
import groovy.xml.dom.DOMCategory

[Node, NodeList, NamedNodeMap, DOMCategory.NodesHolder]*.mixin DOMCategory

def sampleXml = '''
  <sample>
    <someNode anAttribute='foo'>bar</someNode>
  </sample>
'''

def sample = DOMBuilder.parse(new StringReader(sampleXml)).documentElement

println sample.someNode*.tagName
println sample.someNode[0].'@anAttribute'
println sample.someNode[0].attributes['anAttribute']

Gives:

[someNode]
foo
foo
0

精彩评论

暂无评论...
验证码 换一张
取 消