I have an existing XML file and I would like to update some of its attributes. I googled and see many similar questions and answers but I have no luck.
<?xml version="1.0"?>
<system ExportDate="2/15/2018" ExportTime="11:56 AM EST" DateFormat="MM/dd/yyyy" NumberFormat="HH:mm:ss " SchemaValidation="true" ExportVersion="2016.1.SP1710.57 [Build 82] - 27 September 2017 (01:30 IST)" xmlns="http://www.mentor.com/harness/Schema/LibrarySchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mentor.com/harness/Schema/LibrarySchema file:/C:/MentorGraphics/VeSys_Client/dtd/LibrarySchema.xsd" XMLVersion="1.6">
<librarymaterial librarymaterial_id="XXX" description="YYY" materialcode="ZZZ" />
</system>
I am trying to set new values for some of the attributes.
For the root, I have no issue
xmlDoc.DocumentElement.SetAttribute("ExportDate", DateTime.Now.ToShortDateString());
xmlDoc.DocumentElement.SetAttribute("ExportTime", DateTime.Now.ToShortTimeString() + " EST");
However, when I try the different methods but no hope
Method 1:
XmlNode node = xmlDoc.SelectSingleNode("/system/librarymaterial");
node.Attributes["librarymaterial_id"].Value=_librarymaterial_id;
Error:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
node was null.
Method 2:
var nodes = xmlDoc.SelectNodes("/system/librarymaterial");
foreach (XmlElement n in nodes)
{
n.SetAttribute("librarymaterial_id", _librarymaterial_id);
}
This does not create an error, but the librarymaterial_id
does not get updated.