简体   繁体   中英

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

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

Then use the SetElementValue and add the records and finally save it

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

SetElementValue will create the element if not present else would update the existing element

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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