daviderossi.blogspot.com提供了一些帮助,我设法让一些代码用另一个替换xml值
这给了我以下输出,它既编辑了'ix'位置的值,也在最后添加了第二个副本。如果我使用LastIndexOf搜索它并删除它然后删除第一次出现。关于为什么代码可能会这样做,或者如何减轻这种不良影响的任何想法?
def fm_xml = '''<?xml version="1.0" encoding="UTF-8"?>
<MAlong>
<Enquiry.ID>SC11147</Enquiry.ID>
<student.name_middle></student.name_middle>
<student.name_known></student.name_known>
<student.name_previous></student.name_previous>
<student.name_cert>John REnfrew</student.name_cert>
<student.detail_gender>M</student.detail_gender>
<student.sign_name>John Renfrew</student.sign_name>
<student.sign_date>05/01/2010</student.sign_date>
</MAlong>'''
xml = new XmlParser().parseText(fm_xml)
ix = xml.children().findIndexOf{it.name() =='student.name_middle'}
nn = new Node(xml, 'student.name_middle', "NEW")
if (ix != -1 ) {
xml.children()[ix] = nn
nn.parent = xml
}
writer = new StringWriter()
new XmlNodePrinter(new PrintWriter(writer)).print(xml)
result = writer.toString()
RESULT
<MAlong>
<Enquiry.ID>
SC11147
</Enquiry.ID>
<student.name_middle>
NEW
</student.name_middle>
<student.name_known/>
<student.name_previous/>
<student.name_cert>
John REnfrew
</student.name_cert>
<student.detail_gender>
M
</student.detail_gender>
<student.sign_name>
John Renfrew
</student.sign_name>
<student.sign_date>
05/01/2010
</student.sign_date>
<student.name_middle>
NEW
</student.name_middle>
</MAlong>
答案 0 :(得分:1)
使用Groovy类XMLSlurper处理XML可以使代码更容易,并提高可读性。我在Groovy Console上创建了一个示例脚本,您可以在其中对此进行评估:
示例-代码强>
import groovy.xml.StreamingMarkupBuilder
import groovy.xml.XmlUtil
def prettyprint(xml) {
XmlUtil.serialize(new StreamingMarkupBuilder().bind { mkp.yield xml })
}
def input = '''<?xml version="1.0" encoding="UTF-8"?><MAlong>
<Enquiry.ID>SC11147</Enquiry.ID>
<student.name_middle></student.name_middle>
<student.name_known></student.name_known>
<student.name_previous></student.name_previous>
<student.name_cert>John REnfrew</student.name_cert>
<student.detail_gender>M</student.detail_gender>
<student.sign_name>John Renfrew</student.sign_name>
<student.sign_date>05/01/2010</student.sign_date>
</MAlong>'''
def root = new XmlSlurper().parseText(input)
println "Input\n" + prettyprint(root)
// static way
root.'student.name_middle' = "MIDDLE NAME"
// variable way
root.setProperty("student.name_previous", "PREVIOUS NAME")
println "Output\n" + prettyprint(root)
参考: