I am trying to take an XML file containing multiple orders from an online shopping cart, parse it and output the values of each order as its own text file (not XML) using C# and
You can make this super simple. Object oriented programming is the way to go.
So say you create a class Order that takes an XElement. I'll write a couple lines for you.
public class Order
{
XElement self;
public Order(XElement order)
{
self = order;
}
public XElement Element { get { return self; } }
public string OrderNumber
{
// if your xml looks like
get { return (string)(self.Attribute("OrderNumber") ?? (object)"some default value/null"); }
// but if it looks like: somenumber
// get { return (string)(self.Element("OrderNumber") ?? (object)"some default value/null"); }
}
}
You'll have to fill in the rest of the Order's properties yourself. For each Order value, make a property like the OrderNumber I made above. Having properties for each Order value makes accessing the data super simple.
So for your main code you'd have:
XElement file = XElement.Load(@"C:\onlinesales\neworders.xml");
Order[] orders = file.Elements("Order").Select(e => new Order(e)).ToArray();
Now that you have all your orders as individual Order objects, read the data from the list of properties as you output to the file. There's no need now to store the values in StringBuilder's because the values are in the Order objects.
foreach(Order order in orders)
{
// write order.OrderNumber etc. / do whatever you want with the orders.
}