0

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

3
Contributors
3
Replies
4
Views
4 Years
Discussion Span
Last Post by Mike Askew
0

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

0
        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>
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.