how to change XML node values

RJ. picture RJ. · Aug 10, 2012 · Viewed 77.1k times · Source

I have an XML (this is exactly what it looks like):

<PolicyChangeSet schemaVersion="2.1" username="" description="">
    <Attachment name="" contentType="">
        <Description/>
        <Location></Location>
    </Attachment>
</PolicyChangeSet>

This is on the user's machine.

I need to add values to each node: username, description, attachment name, contenttype, and location.

This is what I have so far:

string newValue = string.Empty;
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.Load(filePath);
            XmlNode node = xmlDoc.SelectSingleNode("/PolicyChangeSet");
            node.Attributes["username"].Value = AppVars.Username;
            node.Attributes["description"].Value = "Adding new .tiff image.";
            node.Attributes["name"].Value = "POLICY";
            node.Attributes["contentType"].Value = "content Typeeee";

            //node.Attributes["location"].InnerText = "zzz";

            xmlDoc.Save(filePath);

Any help?

Answer

Jan picture Jan · Aug 10, 2012

With XPath. XmlNode node = xmlDoc.SelectSingleNode("/PolicyChangeSet"); selects your root node.