简体   繁体   English

使用LINQ在xml文件中的特定节点下添加新元素-C#

[英]adding a new element below specific node in a xml file using LINQ - C#

I'm new in C# and I have tried everything during days and days but I have no answers to solve my problem. 我是C#的新手,我日复一日地尝试了一切,但是我没有解决问题的答案。

I have a xml doc like this that populate a treeview in a windows form app: 我有一个像这样的xml文档,它在Windows窗体应用中填充一个树形视图:

<?xml version="1.0" encoding="utf-8" ?>
<root>
<folder title='Standard Elements'>
  <folder title='Screw' >
    <folder title='Type 1' >
      <record title='DIN EN ISO 4762' />
      <record title='DIN EN ISO 7964' />
      <record title='DIN EN ISO 21269' />
    </folder>
    <folder title='Type 2' >
      <record title='DIN EN ISO 4026' />
      <record title='DIN EN ISO 4027' />
      <record title='DIN EN ISO 4028' />
    </folder>
    <folder title='Type 3' >
      <record title='DIN EN ISO 4014' />
      <record title='DIN EN ISO 4017' />
      <record title='DIN EN ISO 4762' />
      <record title='DIN EN ISO 24015' />
    </folder>
  </folder>
  <folder title='Bearing' >
  </folder>
  <folder title='Pin' >
  </folder>
</folder>
  <folder title='Shaft' >
  </folder>
</root>

I have to include a new element below the node with title "Type 2" or other specified node. 我必须在标题为“ Type 2”或其他指定节点的节点下方包括一个新元素。 I'm using Linq in my application but I have no idea to to handle this ensue. 我在应用程序中使用Linq,但我不知道如何处理此问题。

You can use XMLDocument type provided by the framework. 您可以使用框架提供的XMLDocument类型。 Select the node you need, create a new node object and add it as a child to your selected node. 选择所需的节点,创建一个新的节点对象,并将其作为子节点添加到所选节点中。

Your question is similar to this: Modify XML existing content in C# 您的问题与此类似: 在C#中修改XML现有内容

try following : 尝试以下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            XElement type2 = doc.Descendants("folder").Where(x => (string)x.Attribute("title") == "Type 2").FirstOrDefault();

            type2.Add(new XElement("record", new XAttribute("title", "DIN EN ISO 4029")));
        }
    }
}

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

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