Groovy:从文件中读取xml并向其添加节点
我在位置(C:/Users/abc.XML)有一个XML文件abc.XML,我想通过添加一个模块依赖项来更新它 abc.xmlGroovy:从文件中读取xml并向其添加节点,xml,groovy,xml-parsing,Xml,Groovy,Xml Parsing,我在位置(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
<?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>
这不是没有任何错误的工作,相同的代码用于简单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)
您可以参考此处的文档
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)