Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating xml with xdocument

Tags:

c#

xml

linq

I want create xml file of this structure:

 <Devices>
   <Device Number="58" Name="Default Device" >
     <Functions>
         <Function Number="1" Name="Default func" />
         <Function Number="2" Name="Default func2" />
         <Function Number="..." Name="...." />
     </Functions>
   </Device>
 </Devices>

Here's my code:

document.Element("Devices").Add(
new XElement("Device",
new XAttribute("Number", ID),
new XAttribute("Name", Name),
new XElement("Functions")));

Each object "device" have List<> of "functions", how can i add "functions" to xml???

like image 836
Alex F Avatar asked Mar 05 '26 06:03

Alex F


2 Answers

Each object "device" have List<> of "functions", how can i add "functions" to xml???

Really easily - LINQ to XML makes this a doddle:

document.Element("Devices").Add(
    new XElement("Device",
       new XAttribute("Number", ID),
       new XAttribute("Name", Name),
       new XElement("Functions",
           functions.Select(f => 
               new XElement("Function",
                   new XAttribute("Number", f.ID),
                   new XAttribute("Name", f.Name))))));

In other words, you just project your List<Function> to an IEnumerable<XElement> using Select, and the XElement constructor does the rest.

like image 138
Jon Skeet Avatar answered Mar 06 '26 19:03

Jon Skeet


document.Element("Devices").Add(
new XElement("Device",
new XAttribute("Number", ID),
new XAttribute("Name", Name),
new XElement("Functions", from f in functions select new XElement("Function", new XAttribute("Number", f.Number), new XAttribute("Name", f.Name)))));

functions would be your list of functions.
like image 32
Pankaj Mane Avatar answered Mar 06 '26 20:03

Pankaj Mane



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!