【问题标题】:Change Element content in XML file更改 XML 文件中的元素内容
【发布时间】:2021-10-08 18:10:42
【问题描述】:

我在文件“test.xml”中得到下面的 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>

我想将上面显示“panelContainer1”的元素内容更改为“Container456”。我怎样才能做到这一点。我在下面尝试过,但不确定如何访问该内容并进行更改。

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 ?
            }
        }

【问题讨论】:

  • itemElement.Value = "Container456";?

标签: c# xml linq-to-xml


【解决方案1】:

一切看起来都很好。你需要的是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); 

【讨论】:

  • 感谢克里希纳,这很好。但是,如果有更多元素,如 panelContainer1 以及 property name="Visibility">Visible 那么如何过滤仅获取“panelContainer1”?
  • @kami,我已经更新了我的帖子来解决这个场景。请检查
  • 这很好。非常感谢。只有最后一件事是没有对“test.xml”文件进行此更改。如何做到这一点?
  • @kami,请查看更新后的帖子。你只需要 doc.save
  • 简单而伟大。再次感谢@Krishna
猜你喜欢
  • 2021-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-02
  • 2013-05-05
相关资源
最近更新 更多