2011-12-19 42 views
27

Vì vậy, chúng ta hãy giả định này là những gì tôi muốn đạt được:XElement => Thêm trẻ em nút vào thời gian chạy

<root> 
    <name>AAAA</name> 
    <last>BBBB</last> 
    <children> 
    <child> 
     <name>XXX</name> 
     <last>TTT</last> 
    </child> 
    <child> 
     <name>OOO</name> 
     <last>PPP</last> 
    </child> 
    </children> 
</root> 

Không chắc nếu sử dụng XElement là cách đơn giản nhất
nhưng đây là những gì tôi có quá far:

XElement x = new XElement("root", 
        new XElement("name", "AAA"), 
        new XElement("last", "BBB")); 

Bây giờ tôi phải thêm "trẻ em" dựa trên một số dữ liệu tôi có.
Có thể có 1,2,3,4 ...

vì vậy tôi cần phải lặp qua danh sách của tôi để có được mọi trẻ em đơn

foreach (Children c in family) 
{ 
    x.Add(new XElement("child", 
       new XElement("name", "XXX"), 
       new XElement("last", "TTT")); 
} 

VẤN ĐỀ:

Làm theo cách này Tôi sẽ thiếu nút "TRẺ EM TRẺ EM". Nếu tôi chỉ thêm nó trước khi foreach, nó sẽ được trả lại như một nút đóng

<children/> 

và đó không phải là những gì chúng tôi muốn.

HỎI:

Làm thế nào tôi có thể thêm vào phần 1st một nút cha và càng nhiều càng danh sách của tôi có?

Trả lời

29

Hãy thử điều này:

var x = new XElement("root", 
      new XElement("name", "AAA"), 
      new XElement("last", "BBB"), 
      new XElement("children", 
       from c in family 
       select new XElement("child", 
          new XElement("name", "XXX"), 
          new XElement("last", "TTT") 
         ) 
      ) 
     ); 
6
var children = new XElement("children"); 
XElement x = new XElement("root", 
        new XElement("name", "AAA"), 
        new XElement("last", "BBB"), 
        children); 

foreach (Children c in family) 
{ 
    children.Add(new XElement("child", 
       new XElement("name", "XXX"), 
       new XElement("last", "TTT")); 
} 
26
XElement root = new XElement("root", 
        new XElement("name", "AAA"), 
        new XElement("last", "BBB")); 

XElement children = new XElement("children"); 

foreach (Children c in family) 
{ 
    children.Add(new XElement("child", 
       new XElement("name", c.Name), 
       new XElement("last", c.Last)); 
} 
root.Add(children); 
Các vấn đề liên quan