我會嘗試使用LINQ到XML此:
using System;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
XElement root =
new XElement("order",
new XElement("clientId", 1001),
new XElement("config",
new XElement("properties",
new XElement("entry", new XAttribute("key", "RecordTotal"), 10),
new XElement("entry", new XAttribute("key", "InputFileName"), "name"),
new XElement("entry", new XAttribute("key", "ConfigName"), "COMMON"),
new XElement("entry", new XAttribute("key", "DeliveryDate"), "15-FEBRUARY-2013"),
new XElement("entry", new XAttribute("key", "Qualifier"), "name")),
new XElement("id", 19)),
new XElement("orderID", 58239346)
);
Console.WriteLine(root);
}
}
}
通過比較的方式,如果你想多屬性元素所以XML是這樣的:
<order>
<clientId>1001</clientId>
<config>
<properties>
<property>
<entry key="RecordTotal">10</entry>
<entry key="InputFileName">name</entry>
<entry key="ConfigName">COMMON</entry>
<entry key="DeliveryDate">15-FEBRUARY-2013</entry>
<entry key="Qualifier">name</entry>
</property>
<property>
<entry key="RecordTotal">15</entry>
<entry key="InputFileName">othername</entry>
<entry key="ConfigName">UNCOMMON</entry>
<entry key="DeliveryDate">23-FEBRUARY-2013</entry>
<entry key="Qualifier">qname</entry>
</property>
</properties>
<id>19</id>
</config>
<orderID>58239346</orderID>
</order>
你的代碼看起來是這樣的:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
XElement root =
new XElement("order",
new XElement("clientId", 1001),
new XElement("config",
new XElement("properties",
createEntries(getEntries())),
new XElement("id", 19)),
new XElement("orderID", 58239346)
);
Console.WriteLine(root);
}
static IEnumerable<Entry> getEntries()
{
yield return new Entry
{
RecordTotal = 10,
InputFileName = "name",
ConfigName = "COMMON",
DeliveryDate = "15-FEBRUARY-2013",
Qualifier = "name"
};
yield return new Entry
{
RecordTotal = 15,
InputFileName = "othername",
ConfigName = "UNCOMMON",
DeliveryDate = "23-FEBRUARY-2013",
Qualifier = "qname"
};
}
static IEnumerable<XElement> createEntries(IEnumerable<Entry> entries)
{
return from entry in entries
select new XElement(
"property",
new XElement("entry", new XAttribute("key", "RecordTotal"), entry.RecordTotal),
new XElement("entry", new XAttribute("key", "InputFileName"), entry.InputFileName),
new XElement("entry", new XAttribute("key", "ConfigName"), entry.ConfigName),
new XElement("entry", new XAttribute("key", "DeliveryDate"), entry.DeliveryDate),
new XElement("entry", new XAttribute("key", "Qualifier"), entry.Qualifier));
}
}
sealed class Entry
{
public int RecordTotal;
public string InputFileName;
public string ConfigName;
public string DeliveryDate;
public string Qualifier;
}
}
@kingjia我添加了一個完整的'XmlSerializer'示例,FYI – 2013-05-08 08:25:39