kami
kami

Reputation: 269

Change Element content in XML file

I got below XML in file "test.xml"

<MainDoc version="1.0" application="App2">
  <property name="AutoHiddenPanelCaptionShowMode">ShowForAllPanels</property>
  <property name="DockingOptions" isnull="true" iskey="true">
    <property name="DockPanelInTabContainerTabRegion">DockImmediately</property>
  </property>
  <property name="Panels" iskey="true" value="4">
    <property name="Item1" isnull="true" iskey="true">
      <property name="Text">ContainerABC</property>
      <property name="Options" isnull="true" iskey="true">
        <property name="AllowFloating">true</property>
      </property>
    </property>
    <property name="Item2" isnull="true" iskey="true">
      <property name="Text">ContainerXYZ</property>
    </property>
    <property name="Item3" isnull="true" iskey="true">
      <property name="Text">Container123</property>
    </property>
    <property name="Item4" isnull="true" iskey="true">
      <property name="Text">panelContainer1</property>
    </property>
  </property>
</MainDoc>

I want to change element content where it says "panelContainer1" to "Container456" above. How can I do that. I tried below but not sure how to get to that content and change it.

using System.Xml.Linq;

private void button1_Click(object sender, EventArgs e)
        {
            string xmlPath = @"C:\Downloads\test.xml";
            XDocument doc = XDocument.Load(xmlPath);
            var items = from item in doc.Descendants("property")
                        where item.Attribute("name").Value == "Item4"
                        select item;
            foreach (XElement itemElement in items)
            {
                //something here ?
            }
        }

Upvotes: 0

Views: 338

Answers (1)

Krishna Varma
Krishna Varma

Reputation: 4250

Everything is looking good. and what you need is itemElement.Value

XDocument doc = XDocument.Load(xmlPath);
var items = doc.Root.Descendants("property")
                    .Where(x => x.Attribute("name").Value == "Item4")
                    .Descendants()
                    .Where(x=> x.Attribute("name").Value == "Text");

foreach(var itemElement in items)
{
    itemElement.Value = "Container456";
}

doc.Save(xmlPath); 

Upvotes: 1

Related Questions