简体   繁体   English

C#:如何使用 c# 和 foreach 循环将元素添加到 XML

[英]C#: How to add Elements to XML using c# & foreach loop

I´ve got an xml file looking like this:我有一个 xml 文件,如下所示:

<Configuration>
  <Elements>
    <Element>
      <Value1>7</Value1>
    </Element>
    <Element>
      <Value1>3</Value1>
    </Element>
  </Elements>
</Configuration>

I now want to add a Value Element on top of each Element, so that in the end, the xml looks like this:我现在想在每个元素的顶部添加一个值元素,这样最后 xml 看起来像这样:

<Configuration>
  <Elements>
    <Element>
      <Value0>17</Value0>
        <Value1>7</Value1>
    </Element>
    <Element>
      <Value0>13</Value0>
      <Value1>3</Value1>
    </Element>
  </Elements>
</Configuration>

I tried the following in c#:我在 c# 中尝试了以下操作:

        XmlDocument doc = new XmlDocument();
        doc.Load("config.xml");


        XmlElement newelem = doc.CreateElement("Value0");
        
        newelem.InnerText = newValue;

        foreach (XmlNode node in doc.GetElementsByTagName("Element"))
        {
            node.InsertBefore(newelem, node.FirstChild);
        }

This adds the new Value, but only to one Element.这将添加新值,但仅添加到一个元素。 How can I do it, so that it will be added to every Element?我该怎么做才能将其添加到每个元素中? Maybe there is a completely different approach to this.也许有一种完全不同的方法。 I hope one can understand what I`m trying, thanks in advance!我希望有人能理解我在尝试什么,在此先感谢!

Create the element in the for loop.在 for 循环中创建元素。 Here's some working code, using XPath.这是一些工作代码,使用 XPath。

foreach( XmlElement ndNode in xml.SelectNodes( "//Elements/Element")) {
    XmlElement newelem = xml.CreateElement("Value0");
    newelem.InnerText = "test";
    ndNode.InsertBefore(newelem, ndNode.FirstChild);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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