-1

我想用这种格式创建一些 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>

我怎样才能关闭一个节点子或其他东西来拥有我想要的东西?

4

2 回答 2

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>
于 2013-03-08T11:18:31.583 回答
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))));
于 2013-03-08T11:19:32.473 回答