0

I have the following XML

<test>
<one>
    <one1>120</one1>
    <one2>115</one2>
</one>
<two>
    <two1>100</two1>
    <two2>50</two2>
</two>

I need to change the values to the following

<test>
<one>
    <one1>121</one1>
    <one2>116</one2>
</one>
<two>
    <two1>101</two1>
    <two2>51</two2>
</two>

My XML is stored locally. I have written the following groovy code to modify the XML

def xmlFile = "D:/Service/something.xml"
def xml = new XmlParser().parse(xmlFile)
xml.one[0].one1[0].each { 
  it.value = "201"
}
xml.one[0].one2[0].each { 
  it.value = "116"
}

xml.two[0].two1[0].each { 
  it.value = "101"
}
xml.two[0].two2[0].each { 
  it.value = "51"
}

new XmlNodePrinter(new PrintWriter(new FileWriter(xmlFile))).print(xml)

But i am getting this error

Caused by: groovy.lang.ReadOnlyPropertyException: Cannot set readonly property: value for class: java.lang.String

What am i doing wrong?

coderslay
  • 13,960
  • 31
  • 73
  • 121

1 Answers1

2

The node .value() is a method of the Node class. You are looking for the corresponding method setValue method.

def xml = new XmlParser().parseText('<test><one><one1>120</one1><one2>115</one2></one><two><two1>100</two1><two2>50</two2></two></test>');
xml.one[0].one1[0].setValue(121);
xml.one[0].one2[0].setValue(116);
xml.two[0].two1[0].setValue(101);
xml.two[0].two2[0].setValue(51);
Mark
  • 106,305
  • 20
  • 172
  • 230
  • After doing this, do i need to do this also new XmlNodePrinter(new PrintWriter(new FileWriter(xmlFile))).print(xml)...? – coderslay Apr 07 '12 at 18:07
  • If you want to write it back out into a file. – Mark Apr 07 '12 at 18:19
  • If i do that then it is writing to a file, but it is adding lots of white spaces... How to avoid it? – coderslay Apr 07 '12 at 18:24
  • See the answer here: http://stackoverflow.com/questions/5142967/how-to-write-an-xml-to-file-with-just-a-parser-instance for how to avoid all the whitespace. – Mark Apr 07 '12 at 18:51