简体   繁体   中英

Edit XML node in c#

I'm trying to edit a node in .xml file but i can't get it working.

My XML:

<configuration>
  <car title="Ferrari">
    <url>http://www.ferrari.com</url>
  </car>
</configuration>

My code in c#:

    string var_x = "Ferrari";
    XmlDocument doc = new XmlDocument();
    doc.Load("Config.xml");
    XmlNode itemTitle = doc.SelectSingleNode("/configuration/car[@title = '" + var_x + "']");
    XmlNode itemUrl = doc.SelectSingleNode("/configuration/car[@title = '" + var_x + "']/url");


    itemTitle.InnerText = texbox_title.Text;
    itemUrl.InnerText = textbox_url.Text;

    doc.Save("Config.xml");

I can't get code above working for my xml. I can't edit that node. Maybe a problem with XPath but i can't figure out why it's not working properly.

My XML after using c# code above:

<configuration>
  <car title="Ferrari">NEW_NAME</car>
</configuration>

As you want to change the value of the attribute title of the car element, change your code as follows:

 XmlElement itemTitle = (XmlElement)doc.SelectSingleNode("/configuration/car[@title = '" + var_x + "']");
 XmlNode itemUrl = doc.SelectSingleNode("/configuration/car[@title = '" + var_x + "']/url");

 itemTitle.Attributes["title"].Value = texbox_title.Text;
 itemUrl.InnerText = textbox_url.Text;

In your version, the complete inner text of the car element (including the url sub-element) is overwritten by the car title.
In addition, you need to cast the result of SelectSingleNode to XmlElement as this has the Attributes collection.

The property InnerText refers to everything which is text, so you are replacing the content of the car element, including the url element with the line:

itemTitle.InnerText = texbox_title.Text;

Use the following instead:

itemTitle.Attributes["title"].Value = texbox_title.Text;
itemUrl.InnerText = textbox_url.Text;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM