Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would you build this xml in c#

Tags:

c#

xml

asp.net

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>
like image 374
mrblah Avatar asked Nov 24 '09 12:11

mrblah


2 Answers

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();
like image 115
Marc Gravell Avatar answered Sep 29 '22 02:09

Marc Gravell


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")

        )
    )
);
like image 32
Card Visitor Avatar answered Sep 29 '22 02:09

Card Visitor