如何使用 Foreach 遍历集合以构建 XDocument?
Posted
技术标签:
【中文标题】如何使用 Foreach 遍历集合以构建 XDocument?【英文标题】:How can I iterate through a collection with Foreach to build an XDocument? 【发布时间】:2011-03-18 08:10:34 【问题描述】:以下代码给了我错误:
最好的重载方法匹配 'System.Xml.Linq.XElement.XElement(System.Xml.Linq.XName, object)' 有一些无效的参数。
我必须进行哪些更改才能使用 Foreach 构建 XDocument 来遍历我的 List<Customer>
集合?
using System;
using System.Collections.Generic;
using System.Xml.Linq;
namespace test_xml3
class Program
static void Main(string[] args)
List<Customer> customers = new List<Customer>
new Customer FirstName="Jim", LastName="Smith", Age=27,
new Customer FirstName="Hank", LastName="Moore", Age=28,
new Customer FirstName="Jay", LastName="Smythe", Age=44
;
Console.WriteLine(BuildXmlWithLINQ(customers));
Console.ReadLine();
private static string BuildXmlWithLINQ(List<Customer> customers)
XDocument xdoc = new XDocument
(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement("customers",
customers.ForEach(c => new XElement("customer",
new XElement("firstName", c.FirstName),
new XElement("lastName", c.LastName)
)
)
);
return xdoc.Declaration.ToString() + Environment.NewLine + xdoc.ToString();
public class Customer
public string FirstName get; set;
public string LastName get; set;
public int Age get; set;
添加:
感谢您的所有回答,我也想出了这个可行的方法:
private static string BuildXmlWithLINQ2(List<Customer> customers)
XDocument xdoc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes")
);
XElement xRoot = new XElement("customers");
xdoc.Add(xRoot);
foreach (var customer in customers)
XElement xElement = new XElement("customer",
new XElement("firstName", customer.FirstName),
new XElement("lastName", customer.LastName),
new XElement("age", customer.Age)
);
xRoot.Add(xElement);
return xdoc.Declaration.ToString() + Environment.NewLine + xdoc.ToString();
【问题讨论】:
你在代码中缺少一个括号,在... c=> new XElement(...
附近
【参考方案1】:
您必须将customers.ForEach
更改为customers.ConvertAll
。
【讨论】:
【参考方案2】:ForEach 返回 void,而不是对新创建的集合的引用。
以下作品
using System;
using System.Collections.Generic;
using System.Xml.Linq;
using System.Linq;
namespace test_xml3
class Program
static void Main(string[] args)
List customers = new List
new Customer FirstName="Jim", LastName="Smith", Age=27,
new Customer FirstName="Hank", LastName="Moore", Age=28,
new Customer FirstName="Jay", LastName="Smythe", Age=44
;
Console.WriteLine(BuildXmlWithLINQ(customers));
Console.ReadLine();
private static string BuildXmlWithLINQ(List customers)
XDocument xdoc = new XDocument
(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement("customers",
from c in customers select
new XElement("customer",
new XElement("firstName", c.FirstName),
new XElement("lastName", c.LastName)
)
)
);
return xdoc.Declaration.ToString() + Environment.NewLine + xdoc.ToString();
public class Customer
public string FirstName get; set;
public string LastName get; set;
public int Age get; set;
【讨论】:
以上是关于如何使用 Foreach 遍历集合以构建 XDocument?的主要内容,如果未能解决你的问题,请参考以下文章
Java集合遍历方式(for循环与stream()&forEach())比较
java foreach是不是能对jsonarray进行遍历