简体   繁体   English

Groovy xml解析然后重建

[英]Groovy xml parse then rebuild

With more than a little help from daviderossi.blogspot.com I have managed to get some code working to replace an xml value with another 在daviderossi.blogspot.com的帮助下,我设法获得了一些代码来将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()

This give me the following output BUT I would love it to be with properly formed closing tags otherwise XPath queries on the new data will then fail.. 这给了我以下输出,但我希望它具有正确形成的结束标记,否则对新数据的XPath查询将失败。

so for example 所以例如

<student.name_known/>

needs to become 需要成为

<student.name_known></student.name_known>

Any ideas?? 有任何想法吗??

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

<student.name_known/>

格式正确,XPath查询在此XML结构上应能很好地运行。

It should works by setting the expandEmptyElements option to true 它应该通过将expandEmptyElements选项设置为true来工作

see http://groovy.codehaus.org/api/groovy/util/XmlNodePrinter.html#setExpandEmptyElements%28boolean%29 参见http://groovy.codehaus.org/api/groovy/util/XmlNodePrinter.html#setExpandEmptyElements%28boolean%29

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

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