Hello,
I have a rather large XML that I want to to modify during the script. Is there a way to change values in the XML tree using the node search? See below the kind of thing I want to do:
set ((item 1 of all nodes (<<//Field[@FieldName="Ref"]>>) of current_xml)). _attributes.FieldValue = 5
Unfortunately the above does not work, as it seems you are unable set a variable with nodes. Please advise!
p.s.
log ((item 1 of all nodes (<<//Field[@FieldName="Ref"]>>) of current_xml)). _attributes.FieldValue
here is an example to set the Fieldname which is an _Attribute of the _tag Field within the node xml which is a node of testData. Working with xml and trees is a bit fiddely.
I am loading the XML as tree as object which puts it into a nice structure in a sensetalk variable. You can use the debugger to see the actual structure.
set myCXML to {{
<testData>
<xml>
<Field FieldName="Ref" FieldValue="10" />
</xml>
</testData>
}}
put myobj -- {testData:[{xml:[{_tag:"Field", FieldName:"nothing", FieldValue:"10"}]}]}
put myCXML as tree as object into myobj
put myobj.testData.xml's FieldName -- before
Set myobj.testData.xml's FieldName to "nothing"
put myobj.testData.xml's FieldName -- after
Converting a tree to an object is a great way to get a better picture of what you’re working with, and make changes to values before converting it back to a tree.
In this case you can also make a change directly in a node of the tree. The trick is that you need to get a reference to the node and then change that. Here’s an example:
set myXML to {{
<testData>
<xml>
<Field FieldName="Ref" FieldValue="10" />
</xml>
</testData>
}}
put myXML as tree into myTree
put reference to node <<//Field[@FieldName="Ref"]>> of myTree into myNode
put myNode
put myNode's FieldValue
add 3 to myNode's FieldValue
put myNode
put myTree