Hi all, I have question that I have a xml file, I add it to my Project C# Win Form, Now I want to change a value of 1 node or element, so what I need to do? Please give a guide or link or example project to me reference, thank very much.

Here is demo file xml and picture demo.

Collapse | Copy Code

<?xml version="1.0" encoding="utf-8"?>
<data>
    <book>
    <bookID>1111</bookID>
    <bookName>English</bookName>
    <bookPrice>2$</bookPrice>
    </book>
    <book>
    <bookID>222</bookID>
    <bookName>USA</bookName>
    <bookPrice>3$</bookPrice>
    </book>
    <book>
    <bookID>3333</bookID>
    <bookName>Singapore</bookName>
    <bookPrice>4$</bookPrice>
    </book>
</data>

http://i1055.photobucket.com/albums/s505/vn_photo/33-1.jpg

Recommended Answers

All 3 Replies

Member Avatar for Symbiatch

You read it into an XmlDocument, find the correct node using XPath and change the node contents.

        private void UpdateXML(string ElementValue, string NewValue)
        {
            XDocument XDoc = XDocument.Load(XmlFileLocation);
            IEnumerable<XElement> Results = XDoc.Descendants("bookID").Where(node => node.Value == ElementValue);
            foreach (XElement Node in Results)
            {
                Node.SetValue(NewValue);
            }
            XmlWriterSettings XmlSettings = new XmlWriterSettings();
            XmlSettings.Indent = true;
            XmlWriter XmlOut = XmlWriter.Create(XmlFileLocation, XmlSettings);
            XDoc.WriteTo(XmlOut);
            XmlOut.Flush();
            XmlOut.Close();
            MessageBox.Show("Done");
        }

The following you pass an element value (as your example does, it does not pass an element name) and then the method will find all of that value and replace.

With your example data passing '1111' and '2223' as the new value returns the document:

<?xml version="1.0" encoding="utf-8"?>
<data>
  <book>
    <bookID>2223</bookID>
    <bookName>English</bookName>
    <bookPrice>2$</bookPrice>
  </book>
  <book>
    <bookID>222</bookID>
    <bookName>USA</bookName>
    <bookPrice>3$</bookPrice>
  </book>
  <book>
    <bookID>3333</bookID>
    <bookName>Singapore</bookName>
    <bookPrice>4$</bookPrice>
  </book>
</data>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.