示例XML:
<PTC_FareBreakdowns>
<PTC_FareBreakdown>
<PassengerTypeQuantity Code="ADT" Quantity="1" />
<FareBasisCodes>
<FareBasisCode>RGOSAVE</FareBasisCode>
</FareBasisCodes>
<PassengerFare>
<BaseFare Amount="4400" CurrencyCode="INR" />
<Taxes>
<Tax Amount="233" CurrencyCode="INR" TaxCode="OC" TaxGroupCode="SF" TaxGroupName="Taxes &amp; Fees" />
<Tax Amount="218" CurrencyCode="INR" TaxCode="OC" TaxGroupCode="SF" TaxGroupName="Taxes &amp; Fees" />
<Tax Amount="3500" CurrencyCode="INR" TaxCode="YQ" TaxGroupCode="SF" TaxGroupName="Taxes &amp; Fees" />
<Tax Amount="440" CurrencyCode="INR" TaxCode="OC" TaxGroupCode="SF" TaxGroupName="Taxes &amp; Fees" />
<Tax Amount="173" CurrencyCode="INR" TaxCode="OC" TaxGroupCode="SF" TaxGroupName="Taxes &amp; Fees" />
<Tax Amount="0" TaxCode="B2BMarkup" />
</Taxes>
<TotalFare Amount="8964" CurrencyCode="INR" />
<Markups>
<Markup Amount="0.0000" CurrencyCode="INR" Description="0.0 for client - 26472" MarkupCode="DisplayMarkup" Type="M" />
<Markup Amount="0" CurrencyCode="INR" Description="0.0 % on base fare for client - " MarkupCode="DisplayMarkup" MarkupType="M" Type="M" />
<Markup Amount="0" Description="0.0% on fule surcharge 3500.0for client" MarkupCode="DisplayMarkup" MarkupType="M" Type="M" />
</Markups>
</PassengerFare>
</PTC_FareBreakdown>
</PTC_FareBreakdowns>
LINQ,我到目前为止已尝试过,
var Adult = from Main in xd.Descendants(ns + "PTC_FareBreakdown")
from Sub1 in Main.Elements(ns + "PassengerTypeQuantity")
where Sub1.Attribute("Code").Value == "ADT"
from Sub2 in Main.Elements(ns + "PassengerFare").Elements(ns + "Taxes").Elements(ns + "Tax")
where Sub2.Attribute("TaxCode").Value == "OC"
select new
{
OC = Sub2.Attributes("Amount").Sum(nd => Int32.Parse(nd.Value)),
};
它返回值233,218,440和173. 但它必须返回所有值的总和[233 + 218 + 440 + 173 = 1064]。
如果您需要更多信息,请与我们联系。
答案 0 :(得分:1)
var query = xd.Descendants(ns + "PTC_FareBreakdown")
.Elements(ns + "PassengerFare")
.Elements(ns + "Taxes")
.Elements(ns + "Tax")
.Where(tax => (string)tax.Attribute("TaxCode") == "OC")
.Sum(tax => (int)tax.Attribute("Amount"));
结果:1064
答案 1 :(得分:1)
@ lazyberenzovsky使用LINQ关键字语法的答案:
var Adult = (
from tax in xd.Descendants("PTC_FareBreakdown")
.Elements("PassengerFare")
.Elements("Taxes")
.Elements("Tax")
where (string)tax.Attribute("TaxCode") == "OC"
select (int)tax.Attribute("Amount")
).Sum();
当然,您可以使用:
var Adult = (
from tax in xd.Descendants("Tax")
where (string)tax.Attribute("TaxCode") == "OC"
select (int)tax.Attribute("Amount")
).Sum();
如果这是您在XML中唯一拥有Tax
元素的地方。