使用Linq在c#中的XML元素/节点内添加XElement

时间:2013-03-08 11:12:36

标签: c# xml linq linq-to-xml

我想用这种格式创建一些xml

<root>
 <columns>
  <column name="name1" value="value1" />
  <column name="name2" value="value2" />
  <column name="name3" value="value3" />
  ...
 </columns>
 <rows>
  <row name="name1" value="value1" />
  <row name="name2" value="value2" />
  <row name="name3" value="value3" />
  ...
 </rows>
</root>

所以我创建了一个

XElement tree = new XElement("root", new XElement("columns", from c in  columns select new XElement("column", c) ...

结果是

<root>
 <columns>
  <column>
   <column>
    <column> 
     ...
    </column>
   </column>
  </columns>
 ...
</root>

我如何关闭一个节点的孩子或什么东西才能拥有我想要的东西?

2 个答案:

答案 0 :(得分:2)

以下代码:

List<KeyValuePair<string, string>> columns = new Dictionary<string,string> {
   {"name1", "value1"},
   {"name2", "value2"},
   {"name3", "value3"}
}.ToList();

XElement tree =
    new XElement("root",
        new XElement("columns",
            from c in columns
            select new XElement("column",
                new XAttribute("name", c.Key),
                new XAttribute("value", c.Value)
            )
        ),
        new XElement("rows",
             from r in rows // same dictionary as columns 
             select new XElement("row",
                 new XAttribute("name", r.Key),
                 new XAttribute("value", r.Value)
            )
        )
    );

生成所需的xml:

<root>
  <columns>
    <column name="name1" value="value1" />
    <column name="name2" value="value2" />
    <column name="name3" value="value3" />
  </columns>
  <rows>
    <row name="name1" value="value1" />
    <row name="name2" value="value2" />
    <row name="name3" value="value3" />
  </rows>
</root>

答案 1 :(得分:0)

XElement tree = new XElement("root",
    new XElement("columns",
        from c in columns
        select new XElement("column", new XAttribute("name", c.Name,), new XAttribute("value", c.Value))),
    new XElement("rows",
        from r in rows
        select new XElement("row", new XAttribute("name", r.Name,), new XAttribute("value", r.Value))));