2010-07-19 42 views
1

从daviderossi.blogspot.com获得了一些帮助我设法获得了一些代码,用于替换另一个xml值

这给我以下输出,它们都编辑值在'ix'的位置,但最后还增加了第二个副本。如果我使用LastIndexOf搜索并删除它,则删除第一个匹配项。关于为什么代码可能会这样做,或如何减轻这种不良影响的任何想法?

Groovy xml编辑值导致重复

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

结果

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

回答

1

使用Groovy类XMLSlurper与XML的工作使代码更容易,并提高了可读性。我创建的Groovy控制台的示例脚本,你可以评估这个:

例码

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

参考:

+0

整洁,更容易阅读,但将一个错误: [student.name_middle〕是一个常量表达式,但它应该是一个变量表达式 想要探索这个,因为它看起来非常有效。
修复重复值 nn =新节点(null,'student.name_middle',“NEW”) – 2010-07-19 07:53:47

+0

上面的脚本应该按原样运行。我添加了第二个修改语句,显示使用动态名称修改字段。 – stefanglase 2010-07-19 09:51:47

+0

该输出产生一条线。有没有办法用markupbuilder重新创建树? – 2010-07-19 18:38:38