Linq to XML sorting/orderby issue by sorting on subelements
I've got an XML file where a part of it are the GoodsItems
element. I want to order the GoodsItem
elements so that the ones having a subelement SupplementaryInformationLines.SupplementaryInformationLine
with Code == "X002"
and Text != "NLR"
comes first. Subsequently all elements must be ordered by the GoodsItem.TaricCode
element.
<GoodsItems>
<GoodsItem>
<GoodsDescription1>Some goods to be sorted last</GoodsDescription1>
<TaricNumber>854129</TaricNumber>
<SupplementaryInformationLines>
<SupplementaryInformationLine>
<Type>B.H</Type>
<Code>X002</Code>
<Text>NLR</Text>
</SupplementaryInformationLine>
<SupplementaryInformationLine>
<Type开发者_高级运维>SU</Type>
<Code></Code>
<Text>Some text</Text>
</SupplementaryInformationLine>
</SupplementaryInformationLines>
</GoodsItem>
<GoodsItem>
<GoodsDescription1>Some goods to be sorted first</GoodsDescription1>
<TaricNumber>854129</TaricNumber>
<SupplementaryInformationLines>
<SupplementaryInformationLine>
<Type>B.H</Type>
<Code>X002</Code>
<Text>SE_A_4324234</Text>
</SupplementaryInformationLine>
<SupplementaryInformationLine>
<Type>SU</Type>
<Code></Code>
<Text>Some text</Text>
</SupplementaryInformationLine>
</SupplementaryInformationLines>
</GoodsItem>
</GoodsItems>
I tested it and got it to work correctly with the first part of the ordering, then I added the TaricNumber ordering and changed from using .Value to get the string values of the elements in the where clause to casting to string instead since some files got a NullPointerException when using .Value. After these changes I cannot get it to work again. It only orders the GoodsItems by TaricNumber.
var query = from xeGoodsItem in xeCustClearance.Element(nsName + "GoodsItems").Elements(nsName + "GoodsItem")
let sortValue1 = (
from xeSuppInfo in xeGoodsItem.Element(nsName + "SupplementaryInformationLines").Elements(nsName + "SupplementaryInformationLine")
where ((string)xeSuppInfo.Element("Code") == "X002" && (string)xeSuppInfo.Element("Text") != "NLR")
select 1).FirstOrDefault()
orderby sortValue1 descending, (string)xeGoodsItem.Element(nsName + "TaricNumber").Value ascending
select xeGoodsItem;
I don't need to save the XML file with the ordering, I'm only doing the sort in-memory. Although using a ReplaceNode approach instead of a linq query could be a solution as well, I just need to get this thing to work.
Answered in my comment. It was a missing namespace name in front of the element name causing the ordering to not work as expected.
精彩评论