我有以下XML
<OrderReport>
<Item>
<Promotion>
<Component>
<Type>Principal</Type>
<Amount currency="USD">-0.25</Amount>
</Component>
<Component>
<Type>Shipping</Type>
<Amount currency="USD">0.00</Amount>
</Component>
</Promotion>
</Item>
</OrderReport>
我需要获得每种类型的金额。以下是我正在尝试的事情
var q = from orders in xDoc.Descendants("OrderReport")
select new
{
//This should return me the Principal Amount
ItemDiscountAmount = orders.Element("Item")
.Element("Promotion")
.Element("Component")
.Element("Amount")
.Value,
//This should return me the Principal Currency
ItemDiscountCurrency = orders.Element("Item")
.Element("Promotion")
.Element("Component")
.Element("Amount")
.Attribute("currency")
.Value,
//This should return me the Shipping Amount
ShipDiscountAmount = orders.Element("Item")
.Element("Promotion")
.Element("Component")
.Element("Amount")
.Value,
//This should return me the Shipping Currency
ShipDiscountCurrency = orders.Element("Item")
.Element("Promotion")
.Element("Component")
.Element("Amount")
.Attribute("currency")
.Value,
};
我写的代码不正确。它现在返回所有房产的本金金额和货币。评论描述了为了理解目的应该返回的内容。
该查询基本上应该返回价格和货币,具体取决于<Type>
节点下的<Component>
节点。在这种情况下不确定如何设置条件。
答案 0 :(得分:0)
你只需要添加Where子句,
var q = from orders in xdoc1.Descendants("OrderReport")
join ItemPrices in xdoc1.Descendants
where orders.Component.Type == "Principal"
select new
{
OrderId = orders.Element("OrderID"),
City = orders.Element("City"),
CountryRegion = orders.Element("CountryCode"),
State = orders.Element("StateOrRegion"),
Street1 = orders.Element("AddressFieldOne"),
Telephone = orders.Element("PhoneNumber"),
ZipCode = orders.Element("PostalCode"),
Name = orders.Element("Name"),
OrderDate = orders.Element("OrderDate"),
ShipMethod = orders.Element("FulfillmentMethod"),
ItemCode = orders.Element("AmazonOrderItemCode"),
SKU = orders.Element("SKU"),
QtyOrdered = orders.Element(""),
ItemTaxAmount = orders.Element(""),
ItemTaxCurrency = orders.Element(""),
ItemShipTaxAmount = orders.Element(""),
ItemShipTaxCurrency = orders.Element(""),
ItemTotalAmount = orders.Element(""),
ItemTotalCurrency = orders.Element(""),
ItemUnitPrice = orders.Element(""),
ItemCommissionAmount = orders.Element(""),
ItemCommissionCurrency = orders.Element("")
};
答案 1 :(得分:0)
如果您首先找到包含Principal
类型或Shipping
类型的元素,然后获取所需的值,将会有所帮助。我相信这就是你所追求的。
// using an XPATH will make this nicer to express
var query = from report in xDoc.Descendants("OrderReport")
let principalAmount = report.XPathSelectElement("./*/*/Component[Type='Principal']/Amount")
let shippingAmount = report.XPathSelectElement("./*/*/Component[Type='Shipping']/Amount")
select new
{
ItemDiscountAmount = (decimal)principalAmount,
ItemDiscountCurrency = (string)principalAmount.Attribute("currency"),
ShipDiscountAmount = (decimal)shippingAmount,
ShipDiscountCurrency = (string)shippingAmount.Attribute("currency"),
};
请记住要包含名称空间System.Xml.XPath
,以便工作。