I have the following xml
<?xml version="1.0" encoding="UTF-8"?>
<Actions>
<add order-id="1" symbol="ABC" price="5" quantity="200" />
<add order-id="2" symbol="123" price="15" quantity="100" />
<add order-id="3" symbol="ABC" price="5" quantity="300" />
<add order-id="4" symbol="ABC" price="7" quantity="150" />
<edit order-id="1" price="7" quantity="200" />
<remove order-id="4" />
<add order-id="5" symbol="123" price="17" quantity="300" />
<add order-id="6" symbol="123" price="12" quantity="150" />
<edit order-id="3" price="7" quantity="200" />
<remove order-id="5" />
</Actions>
I need to parse this using linq into the following object structure:
internal class OrderAction
{
private readonly Action action;
private readonly Order order;
public Action Action { get { return action; }}
public Order Order { get { return order; }}
public OrderAction(Action action,Order order)
{
this.action = action;
this.order = order;
}
}
where an action is public enum Action { ADD, REMOVE, EDIT }
an order is as follows:
class Order
{
public Order(long orderId, String symbol, int price, int quantity)
{
this.orderId = orderId;
this.symbol = symbol;
this.price = price;
this.quantity = quantity;
}
public long orderId { get; private set; }
public String symbol { get; private set; }
public int price { get; private set; }
public int quantity { get; private set; }
}
I need to load the xml into an xdocument and find all the IEnumerable of orderactions in the file. How can i do this, without resorting into serialization attributes?
What should the values of the missing Order
properties be in case of "edit and "remove"? I assumed the default values for string
and int
...
This would be the LINQ statement (assuming that your XDocument
is called doc
):
var result = doc
.Root
.Elements()
.Select(elem => new OrderAction
(
(Action)Enum.Parse(typeof(Action), elem.Name.LocalName.ToUpper()),
new Order
(
elem.Attributes("order-id").Select(x => long.Parse(x.Value)).FirstOrDefault(),
elem.Attributes("symbol").Select(x => x.Value).FirstOrDefault(),
elem.Attributes("price").Select(x => int.Parse(x.Value)).FirstOrDefault(),
elem.Attributes("quantity").Select(x => int.Parse(x.Value)).FirstOrDefault()
)
));
here's my best shot
XElement doc = XElement.Load("d:\\tst.xml");
List<OrderAction> lst = doc.Elements().Select(x =>
new OrderAction(
(Action)
Enum.Parse(typeof (Action),
x.Name.ToString().ToUpper()),
new Order(
long.Parse(x.Attribute("order-id").Value),
x.Attribute("symbol") != null ? x.Attribute("symbol").Value : "",
x.Attribute("price") != null ? int.Parse(x.Attribute("price").Value) : 0,
x.Attribute("quantity") != null ? int.Parse(x.Attribute("quantity").Value): 0))
).ToList();
it took me a while... i'm not used to that big of linq parse
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.