我正在尝试使用linq读取XML文档。我遇到了一个问题一个节点有两个同名的值我怎么才能得到这两个值。使用此代码,我只能获得第一个。
XDocument doc = XDocument.Load("Orders.xml");
var data = from item in doc.Descendants("Order")
select new
{
OrderID = item.Element("OrderID").Value,
POnumber = item.Element("PurchaseOrderNumber").Value,
OrderDate = item.Element("OrderPlacedDate").Value,
PFirstName = item.Element("purchasingContact").Element("FirstName").Value,
Pid= item.Element("CurrentOrderDetails").Element("ProductsId").Value
};
我只能得到产品id 34,我怎么能得到另一个呢?请帮助
<Order>
<OrderID>123</OrderID>
<PurchaseOrderNumber>12</PurchaseOrderNumber>
<OrderPlacedDate>12/23/2012</OrderPlacedDate>
<PurchasingContact>
<FirstName>test</FirstName>
</PurchasingContact>
<CurrentOrderDetails>
<ProductsId>34</ProductsId>
<OrderQuantity>2</OrderQuantity>
<ProductsId>35</ProductsId>
<OrderQuantity>2</OrderQuantity>
</CurrentOrderDetails>
</Order>
<Order>
.......
</Order>
XDocument doc = XDocument.Load("Orders.xml");
var data = from item in doc.Descendants("Order")
select new
{
OrderID = item.Element("OrderID").Value,
POnumber = item.Element("PurchaseOrderNumber").Value,
OrderDate = item.Element("OrderPlacedDate").Value,
PFirstName = item.Element("purchasingContact").Element("FirstName").Value,
Pids = item.Element("CurrentOrderDetails").Elements("ProductsId").Select(e => e.Value).ToList()
};
但是老实说,您应该考虑更改XML结构。CurrentOrderDetails
应该看起来更像这样:
<CurrentOrderDetails>
<Product id="34" quantity="2" />
<Product id="35" quantity="2" />
</CurrentOrderDetails>
或
<CurrentOrderDetails>
<Product>
<Id>34</Id>
<Quantity>2</Quantity>
</Product>
<Product>
<Id>35</Id>
<Quantity>2</Quantity>
</Product>
</CurrentOrderDetails>
这样可以更容易地获得产品ID和它的数量。
from o in doc.Descendants("Order")
let contact = o.Element("purchasingContact")
let details = o.Element("CurrentOrderDetails")
select new {
OrderID = (int)o.Element("OrderID"),
POnumber = (int)o.Element("PurchaseOrderNumber"),
OrderDate = (DateTime)o.Element("OrderPlacedDate"),
PFirstName = (string)contact.Element("FirstName"),
Pids = details.Elements("ProductsId").Select(e => (int)e).ToList()
};
如果您希望在结构中使用数组形式的pid,则可以使用
Pids = item.Element("CurrentOrderDetails")
.Elements("ProductsId")
.Select(e => e.Value).ToArray()
如果你想让你所有的条目都是一个平面列表,你可以使用
var data = from item in doc.Descendants("Order")
from product in item.Element("CurrentOrderDetails").Elements("ProductsId")
select new
{
OrderID = item.Element("OrderID").Value,
POnumber = item.Element("PurchaseOrderNumber").Value,
OrderDate = item.Element("OrderPlacedDate").Value,
PFirstName = item.Element("purchasingContact")
.Element("FirstName").Value,
Pid = product.Value
};
顺便说一下:XML模型应该在productsid和orderquantity周围有一个环绕元素,并显式地对订单行进行建模。