将属性添加到DOM文档/元素的根标记

时间:2013-05-31 12:15:28

标签: xml dom groovy

我希望能够将命名空间声明属性添加到DOM文档/元素的根标记。

Codewise,我想从这样的事情出发:

<xsl:stylesheet 
    xmlns:xlink="http://www.w3.org/TR/xlink/"
    xmlns="http://www.w3.org/1999/xhtml">

对此:

<xsl:stylesheet 
    xmlns:xlink="http://www.w3.org/TR/xlink/"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:util="http://www.url.to.util"> <-- New namespace declaration

我目前正在尝试做什么:

xsl.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:util", "http://www.url.to.util")

但显然,这是行不通的。但是我怎么能这样做呢?

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

不知道你正在使用的上下文的约束。这是使用DOMBuilder处理它的一种方法:

import groovy.xml.DOMBuilder
import groovy.xml.XmlUtil

def xmlxsl = '''
<xsl:stylesheet 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xlink="http://www.w3.org/TR/xlink/"
    xmlns="http://www.w3.org/1999/xhtml" />
'''
def doc = DOMBuilder.parse(new StringReader(xmlxsl))
def ele = doc.getDocumentElement()
ele.setAttribute("xmlns:util","http://www.url.to.util")

assert XmlUtil.serialize(ele).trim() == 
        '<?xml version="1.0" encoding="UTF-8"?>' +
        '<xsl:stylesheet xmlns="http://www.w3.org/1999/xhtml"' +
        ' xmlns:util="http://www.url.to.util"' +
        ' xmlns:xlink="http://www.w3.org/TR/xlink/"' +
        ' xmlns:xsl="http://www.w3.org/1999/XSL/Transform"/>'

请注意,在断言字符串中,ele的结果包含所需的xmlns:util="http://www.url.to.util"。在您的系统上,我不确定命名空间的顺序是否相同。但是,应该加上它。

我添加到原始示例命名空间的一个细节是xmlns:xsl="http://www.w3.org/1999/XSL/Transform",因此xsl命名空间本身会验证。

处理编辑命名空间的另一种方法可以在这篇文章中找到(也在Stack Overflow上):Use of Namespaces in Groovy MarkupBuilder