比 DOMCategory 更好的处理 dom 的方式?

发布于 2024-09-03 15:17:35 字数 132 浏览 2 评论 0原文

我正在尝试创建一个可以轻松使用 dom 节点的 DSL。使用 DOMCategory 很好,但会增加“use(DOMCategory)”的噪音。有办法避免这种情况吗?

我尝试将脚本调用包装在“use”调用中,但这似乎在闭包中不起作用。

I'm trying to create a DSL 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

灵芸 2024-09-10 15:17:35

您可以使用 groovy 的运行时 mixin 功能来永久混合该类别。 Class.mixin 将类别中适用的方法添加到类的元类中。将其应用于作为每个类别方法的第一个参数出现的类和接口,并且类别将可用,而无需将代码包含在 use(DOMCategory) 块中。

示例:

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']

给出:

[someNode]
foo
foo

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文