如何在XML文档中的特定位置添加XElement [英] how to add XElement in specific location in XML Document

查看:63
本文介绍了如何在XML文档中的特定位置添加XElement的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个这样的XML文档:

I want to create an XML document like this:

我想使用代码和LINQ-to-XML从头开始创建它.在加载事件"表单中,我编写了以下代码:

I want to create it from scratch using code and LINQ-to-XML. In the form Load Event I've written this code:

private void Form9_Load(object sender, EventArgs e)
{
    doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"));
    XElement myroot = new XElement("Employees");
    doc.Add(myroot);
}

如何将新人员添加到员工中,如果我想在特定位置插入人员,我该怎么办?

How I can add new person to Employees, and if I want to insert person in specific location what can I do?

我如何删除或更新特定的人?

How I can delete or update a specific person ?

推荐答案

搜索要添加的元素并使用Add方法如下图

Search element you want to add and use Add method as shown below

xDoc.Element("content")
    .Elements("item")
    .Where(item => item.Attribute("id").Value == "2").FirstOrDefault()
    .AddAfterSelf(new XElement("item", "C", new XAttribute("id", "3")));

<Microsoft>
<DOTNet>

</DOTNet>
</Microsoft>


private void addToXml()
{
   XDocument xmlDoc = XDocument.Load("yourfile.xml");

  xmlDoc.Element("Microsoft").Add(new XElement("DOTNet", new XElement("Name", "Nisar"),
      new XElement("Forum", "dotnetobject"), new XElement("Position", "Member")));
    xmlDoc.Save("yourfile.xml");
  readXml();
}

<Microsoft>
<DOTNet>
  <Name>Nisar</Name>
  <Forum>dotnetobject</Forum>
  <Position>Member</Position>
</DOTNet>
</Microsoft>

这篇关于如何在XML文档中的特定位置添加XElement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆