如果您使用的是 .net 3.5,则可以使用 XLINQ。这是来自http://blogs.msdn.com/wriju/archive/2007/02/20/xlinq-create-xml-from-object-using-linq.aspx的示例
如果您在“xlinq create”上进行谷歌搜索, 您会发现很多示例(我在想,您可能对 RSS 示例最感兴趣。
var objCust = new[]
{
new {CustID = 2, CustName = "Sumitra", Phone = "123-123-1236"},
new {CustID = 3, CustName = "Wriju", Phone = "123-123-1235"},
new {CustID = 4, CustName = "Writam", Phone = "123-123-1234"},
new {CustID = 1, CustName = "Debajyoti", Phone = "123-123-1237"}
};
XElement _customers = new XElement("customers",
from c in objCust
orderby c.CustID //descending
select new XElement("customer",
new XElement("name", c.CustName),
new XAttribute("ID", c.CustID),
new XElement("phone", c.Phone)
)
);
Console.WriteLine(_customers);
输出将如下所示:
<customers>
<customer ID="1">
<name>Debajyoti</name>
<phone>123-123-1237</phone>
</customer>
<customer ID="2">
<name>Sumitra</name>
<phone>123-123-1236</phone>
</customer>
<customer ID="3">
<name>Wriju</name>
<phone>123-123-1235</phone>
</customer>
<customer ID="4">
<name>Writam</name>
<phone>123-123-1234</phone>
</customer>
</customers>