次の構造の XML ファイルに取り組んでいます。
<vco:ItemDetail>
<cac:Item>
...
<cac:RecommendedRetailPrice>
<cbc:PriceAmount amountCurrencyID="EUR">4.95</cbc:PriceAmount>
<cbc:BaseQuantity quantityUnitCode="EA">1</cbc:BaseQuantity>
</cac:RecommendedRetailPrice>
...
</cac:Item>
...
</vco:ItemDetail>
RecommendedRetailPrice
and/orはすべてのPriceAmount
に存在しない場合がありますItem
。Items
それでも、すべてをそれぞれので並べ替えたいと思いますRecommendedRetailPrices
。そのため、うまく機能する次のコードになりましたが、ネストされた if ステートメントのすべての段階で null をチェックする必要があります。
//full_xml is of type XDocument
var most_expensive = full_xml
.Element("ItemDetails")
.Elements(vco + "ItemDetail")
.Elements(cac + "Item")
.OrderBy(el =>
{
var rrp = el.Element(cac + "RecommendedRetailPrice");
string val = null;
if(rrp != null) {
var pa = rrp.Element(cbc + "PriceAmount");
if(pa != null) {
val = rrp.Value;
}
}
if (val != null) {
return Convert.ToDouble(val);
}
else {
return 0.0;
}
}
)
.Last();
この場合、これはそれほど悪くないかもしれませんが、これを行うにはもっと慣用的な方法が必要だと思います。8 レベル下のオプションの子ノードでソートすることを検討してください。
どんな助けでも感謝します。