【问题标题】:Add an attribute to the root tag of a DOM Document/Element将属性添加到 DOM 文档/元素的根标记
【发布时间】:2013-05-27 06:14:57
【问题描述】:

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

在代码方面,我想从这样的事情开始:

<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")

但很明显,这是行不通的。不过,我该怎么做呢?

提前感谢您的帮助!

【问题讨论】:

    标签: xml dom groovy


    【解决方案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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-22
      • 2016-01-02
      • 1970-01-01
      • 1970-01-01
      • 2013-03-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多