I need to generate this simple looking XML, looking for a clean way to generate it.
<order>
<user>2343></user>
<creditcardtype>2333></creditcarttype>
<country>USA</country>
<orderDetails>
<amount>23434</amount>
<shipping>32</shipping>
</orderDetails>
</order>
Since XDocument
is taken, here's an XmlWriter
answer:
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();
Or with 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();
use XDocument class, so code will be like
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")
)
)
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With