2012-08-06 2 views
1

Я хочу создать XML-файл этой структуры:Создание XML с XDocument

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

Вот мой код:

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

Каждый объект "устройство" есть список <> из "функций", как может Я добавляю «функции» в xml ???

ответ

8

В каждом объекте «устройство» есть список <> «функции», как я могу добавить «функции» в xml ???

Действительно легко - LINQ к XML делает это пустяк:

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

Другими словами, вы просто проецировать List<Function> к IEnumerable<XElement> с помощью Select и XElement конструктор делает все остальное.

+1

спасибо, очень просто –

1
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. 
Смежные вопросы