繁体   English   中英

Groovy:从文件读取xml并向其中添加节点

[英]Groovy : Reading xml from a file and adding node to it

我在位置(C:/Users/abc.xml)有一个XML文件,说abc.xml,我想通过添加一个模块依赖性来更新它。

abc.xml

<?xml version="1.0" encoding="UTF-8"?>

<!--
  ~ This is free software; you can redistribute it and/or modify it
  ~ under the terms of the GNU Lesser General Public License as
  ~ published by the Free Software Foundation; either version 2.1 of
  ~ the License, or (at your option) any later version.
  -->

<module xmlns="urn:jboss:module:1.3" name="org.picketbox">
    <!-- This module is deprecated and subject to being removed in a subsequent release. -->
    <properties>
      <property name="jboss.api" value="deprecated"/>
    </properties>

    <resources>
        <resource-root path="picketbox-4.9.6.Final.jar"/>
        <resource-root path="picketbox-infinispan-4.9.6.Final.jar"/>
        <resource-root path="picketbox-commons-1.0.0.final.jar"/>
    </resources>

    <dependencies>
        <module name="javax.api"/>
        <module name="javax.persistence.api" optional="true"/>
    </dependencies>
</module>

我试图通过下面的代码在依赖项部分添加模块名称=“ javax.xyz”

def fileLocation = "C:/Users/abc.xml"
def abcXML = new XmlSlurper().parse(new File(fileLocation))
abcXML.dependencies.appendNode {
     module {
         name 'javax.xyz'
     }
}
XmlUtil.serialize(abcXML); 

这不能正常工作,相同的代码适用于简单的xml(没有任何注释,只有一个节点)文件。

尝试这个

import groovy.xml.QName
import groovy.xml.XmlUtil

def xml = new File("C:/Users/abc.xml").text
def parser = new XmlParser()
def root = parser.parseText(xml)
def numberOfResults = parser.createNode(root.dependencies[0], new QName("module"), ["name":"javax.xyz"])
println XmlUtil.serialize(root)

您可以在此处参考文档http://groovy-lang.org/processing-xml.html#_adding_nodes

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM