Click here to Skip to main content
15,907,497 members
Please Sign up or sign in to vote.
1.40/5 (3 votes)
See more:
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.

HTML
<edit lang="xml"><?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></edit>


http://i1055.photobucket.com/albums/s505/vn_photo/222.jpg[^]
Posted
Updated 3-May-17 11:24am
v5

 
Share this answer
 
C#
private void button1_Click(object sender, EventArgs e)
        {
            DataSet ds = new DataSet();
            string strBookID = "1111";
            string strBookCurName = "English";
            string strBookNewName = "Koria";
            ds.ReadXml("data.xml");
            if (ds.Tables.Count != 0)
            {
                for (int intLoop = 0; intLoop < ds.Tables[0].Rows.Count; intLoop++)
                {
                    if (ds.Tables[0].Rows[intLoop]["bookID"].ToString() == strBookID)
                    {
                        if (ds.Tables[0].Rows[intLoop]["bookName"].ToString() == strBookCurName)
                        {
                            ds.Tables[0].Rows[intLoop]["bookName"] = strBookNewName;
                            ds.AcceptChanges();
                        }
                    }
                }
                ds.WriteXml("data.xml");
            }


        }
 
Share this answer
 
There are various ways to achieve the same.

If you want to keep reading sequentially, you can use XmlReader.

If you want to read/update/delete/insert at particular location, you can use two approaches
1. XmlDocument and XPath.
2. LinQ to XML

For XmlDocument approach, First you declare variable and load xml.

C#
XmlDocument xDoc = new XmlDocument();
xDoc.Load("YourFile.Xml");

Then, you read like
C#
string nodeValue = xDoc .DocumentElement.SelectSingleNode("NodeName").InnerText;


You can update value like
C#
xDoc.DocumentElement.SelectSingleNode("NodeName").InnerText = newValue;

Note, that in above code, "NodeName is actually Xpath. You can give it like Node/ChildNode/GrandChildNode and so on. You can find more details about xPath at http://www.w3schools.com/xpath/default.asp[^]

Hope that helps. If it does mark it as answer/upvote.

Thanks
Milind
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900