View Full Version : XML SetValue element path issue
Keiths123
11-20-2009, 05:36 AM
I have an xml file with the following type of format:
<Root>
<TopLevel>
<Setting ID="1">
<Val>a</Val>
</Setting>
<Setting ID="2">
<Val>b</Val>
</Setting>
</TopLevel>
</Root>
Can someone please tell me how to modify the <Val> item for the Setting with an ID of 2?
Thanks in advance,
Keith
Ulrich
11-23-2009, 12:34 PM
Just one possible way:
-- set up control variables
found = false;
count = 1;
-- load the XML file
XML.Load("C:\\test.xml");
-- step through the XML until I find attribute "ID=2"
while not found do
attr = XML.GetAttribute("Root/TopLevel/Setting:"..count, "ID");
if (attr ~= "") then
if (attr == "2") then
found = true;
else
count = count + 1;
end
else
-- abort loop on error
break;
end
end
if (found) then
val = XML.GetValue("Root/TopLevel/Setting:"..count.."/Val");
-- display former value?
Dialog.Message("info", "Val=" .. val, MB_OK);
-- now set the new value
newval = "this is new";
XML.SetValue("Root/TopLevel/Setting:"..count.."/Val", newval);
-- save the modified XML
XML.Save("C:\\new.xml");
end
Ulrich
halshaikh
04-23-2010, 02:50 PM
This code may help me too.
Lorne
04-23-2010, 04:01 PM
There's an easier way using attribute predicates (which are an undocumented feature of the XML actions).
-- set the value to "foo" using a predicate to search for a Settings node with an ID attribute whose value is 2
XML.SetValue("Root/TopLevel/Setting[@ID='2']/Val", "foo");
This is equivalent to navigating like so:
Root -> TopLevel -> first Setting with an ID attribute whose value is 2 -> Val
A more complete example:
-- example XML for this test
XML.SetXML([[<Root>
<TopLevel>
<Setting ID="1">
<Val>a</Val>
</Setting>
<Setting ID="2">
<Val>b</Val>
</Setting>
</TopLevel>
</Root>
]]);
-- get the existing value, using a predicate to search for Val under a parent Setting node with an ID attribute whose value is "2"
val = XML.GetValue("Root/TopLevel/Setting[@ID='2']/Val");
Dialog.Message("The current value is",val);
-- set the value to "foo"
XML.SetValue("Root/TopLevel/Setting[@ID='2']/Val", "foo");
val = XML.GetValue("Root/TopLevel/Setting[@ID='2']/Val");
Dialog.Message("The new value is",val);
Powered by vBulletin™ Version 4.0.6 Copyright © 2012 vBulletin Solutions, Inc. All rights reserved.