I am writing a function to update my XML and am having some issues. I’d hoped I could just set old XElement directly to the updated one but that doesn’t work in the foreach loop (though should only ever be one query result). I was going to hard-code each field, but then decided to use a loop. However when it hits the section and it’s sub-elements it reads it all as a single element and messed up the file
var myDevice = from c in appDataXml.Descendants("device")
where (string)c.Element("name") == App.CurrentDeviceName
&& (string)c.Element("ip") == App.CurrentIp
select c;
if (myDevice.Any())
{
foreach (XElement device in myDevice)
{
//device.Element("customname").Value = updatedDevice.Element("customname").Value;
for (int a = 0; a < device.Elements().Count(); a++)
{
string field = device.Elements().ElementAt(a).Name.ToString();
device.Element(field).Value = updatedDevice.Element(field).Value;
}
}
}
sample XML
<Devices>
<device>
<name>blah</name>
<customname>custom</customname>
<ip>192.168.1.100</ip>
<port>1000</port>
<sources>
<source>
<code>00</code>
<name>blah2</name>
<hidden>False</hidden>
</source>
<source>
...etc
</sources>
</device>
You need to abstract (make classes) of your xml, it will help you CRUD and search it.
Example: (using these extensions: http://searisen.com/xmllib/extensions.wiki)
An example using it:
It is a change in the way of thinking, so instead of worrying about how to reference a value, you create the class to read/write to the xml, and instead you just get/pass off data to a class, that then reads/writes the xml.
Edit:
—- Add to XElementConversions class —-
To be consistent with the file, and to work properly I made detailed versions. You can modify them to make the other types, like bool, DateTime, etc.