2010-07-19 73 views
0

比從daviderossi.blogspot.com我已經得到了一些幫助更多的得到一些代碼的工作,以取代另一個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() 

XML值這給我下面的輸出,但我喜歡它,是用正確形成結束標記,否則XPath查詢新數據,然後將失敗..

因此,例如

<student.name_known/> 

需求,成爲

<student.name_known></student.name_known> 

任何想法??

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

回答

2

<student.name_known/>

是完全中規中矩,和XPath查詢應該便能很好地工作在這個XML結構。

+0

認爲我有一個複製和粘貼錯誤,它確實沒有工作,但仍有意使其稍微更具可讀性 – 2010-07-19 06:41:24

+0

一般來說,您沒有這種使用XML解析的控制級別。我沒有看到Groovy有任何明顯的'漂亮打印'選項,但任何解決方案可能都不值得。 – Dunderklumpen 2010-07-20 03:39:17