简体   繁体   English

如何使用linq2xml插入xml节点?

[英]How to insert xml node using linq2xml?

I know how to read, but can't find how to edit, also I want to ask how to insert ? 我知道如何阅读,却找不到如何编辑,也想问一下如何插入?

my xml file is looking like : 我的xml文件看起来像:

<?xml version="1.0"?>
<dataWorkers>
    <worker name="1" workshop="2" salary="25000"/>
    <worker name="3" workshop="4" salary="25000"/>
</dataWorkers>

thank you. 谢谢。

First Load the xml doc 首先加载xml文档

XElement el = XElement.Load(@"yourfile.xml");

Then use the SetElementValue and add the records and finally save it 然后使用SetElementValue并添加记录,最后将其保存

elem.SetElementValue("2","5", "150000");
el.Save("yourfile.xml");

SetElementValue will create the element if not present else would update the existing element SetElementValue将创建元素(如果不存在),否则将更新现有元素

Insert : 插入 :

XElement.Add (new XElement("el"));

Edit: 编辑:

var el = xDocument.Root.Elements("worker").First();
el.Attribute ("name").SetValue ("name1");
xDocument.Save();
XElement dataWorkers=  new XElement("worker", 
                                    new XAttribute("name", 1),

                                    new XAttribute("workshop", 2),

                                    new XAttribute("salary",25000)

//another way to add a worker to dataWorkers
XElement worker = new XElement("worker");
            XAttribute name = new XAttribute("name",1);
            XAttribute workshop = new XAttribute("workshop",4);
            XAttribute salary = new XAttribute("salary",25000);
            worker.Add(name);
            worker.Add(workshop);
            worker.Add(salary);
dataWorkers.Add(worker);

XDocument myXml= new XDocument( new XDeclaration("1.0", "UTF-8", "true"),
                                new XElement(dataWorkers));      

For better understanding check LINQ to XML - 5 Minute Overview and Understanding C#: Simple LINQ to XML examples (tutorial) 为了更好地理解,请检查LINQ to XML-5分钟概述理解C#:简单的LINQ to XML示例(教程)

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

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