我需要生成这个简单的XML,寻找一种简洁的方法来生成它。
<order>
<user>2343></user>
<creditcardtype>2333></creditcarttype>
<country>USA</country>
<orderDetails>
<amount>23434</amount>
<shipping>32</shipping>
</orderDetails>
</order>
答案 0 :(得分:11)
使用XDocument类,所以代码就像
XDocument srcTree = new XDocument(
new XElement("order",
new XElement("user", "2343"),
new XElement("creditcardtype", "2333"),
new XElement("country", "USA"),
new XElement("orderDetails",
new XElement ("amount", "23434"),
new XElement ("shipping", "32")
)
)
);
答案 1 :(得分:11)
自XDocument
采取后,这是一个XmlWriter
答案:
StringWriter sw = new StringWriter();
using (XmlWriter xw = XmlWriter.Create(sw)) {
xw.WriteStartElement("order");
xw.WriteElementString("user", "2343");
xw.WriteElementString("creditcardtype", "2333");
xw.WriteElementString("country", "USA");
xw.WriteStartElement("orderDetails");
xw.WriteElementString("amount", "23434");
xw.WriteElementString("shipping", "32");
xw.WriteEndElement();
xw.WriteEndElement();
}
string s = sw.ToString();
或XmlSerializer
:
[XmlRoot("order")] public class Order {
[XmlElement("user")] public int User { get; set; }
[XmlElement("creditcardtype")] public int CreditCardType { get; set; }
[XmlElement("country")] public string Country { get; set; }
[XmlElement("orderDetails")] public OrderDetails Details { get; set; }
}
public class OrderDetails {
[XmlElement("amount")] public int Amount { get; set; }
[XmlElement("shipping")] public int Shipping { get; set; }
}
....
var order = new Order {
User = 2343, CreditCardType = 2333, Country = "USA",
Details = new OrderDetails {
Amount = 23434,
Shipping = 32
}
};
XmlSerializer ser = new XmlSerializer(order.GetType());
StringWriter sw = new StringWriter();
ser.Serialize(sw, order);
string s = sw.ToString();
答案 2 :(得分:4)
请参阅LINQ to XMl方法来做到这一点,就像这样
XDocument doc = new XDocument(new XElement("order",
new XElement("user", "2343"),
new XElement("creditcardtype", "2333"),
new XElement("country", "USA"),
new XElement("orderDetails",
new XElement("amount", "23434"),
new XElement("shipping", "32"))));
doc.Save("myxml.xml");
答案 3 :(得分:2)
XmlDocument xml = new XmlDocument();
XmlElement order = xml.CreateElement("order");
xml.AppendChild(order);
XmlElement user = xml.CreateElement("user");
user.InnerText = "2343";
order.AppendChild(user);
XmlElement ccType = xml.CreateElement("creditcardtype");
ccType.InnerText = "2333";
order.AppendChild(ccType);
等
答案 4 :(得分:1)
xsd.exe
根据给定的XML文件自动生成架构。)xsd.exe /classes
根据您的XML架构生成C#类。XmlSerializer
类从/向C#对象结构序列化/反序列化XML。还有codeproject article描述了这种方法。
答案 5 :(得分:0)
我会使用Linq to XML建议,但为了完整起见,我只需要添加这个:
var xe = XElement.Parse("<order><user>2343</user><creditcardtype>2333</creditcarttype><country>USA</country><orderDetails><amount>23434</amount><shipping>32</shipping></orderDetails></order>");
:)