问题
Following question Filter xml with LINQ2XML
After succesfully filtering (removing nodes) from a xml file. I'd like to order by some attribute in nodes.
Sample of xml file:
<Root>
<Group Price="50">
<Item Price="60"/>
<Item Price="50"/>
<Item Price="70"/>
</Group>
<Group Price="55">
<Item Price="62"/>
<Item Price="57"/>
<Item Price="55"/>
</Group>
<Group Price="61">
<Item Price="62"/>
<Item Price="61"/>
<Item Price="65"/>
</Group>
<!--More Group Nodes-->
</Root>
And I'd like to get:
<Root>
<Group Price="61">
<Item Price="65"/>
<Item Price="62"/>
<Item Price="61"/>
</Group>
<Group Price="55">
<Item Price="62"/>
<Item Price="57"/>
<Item Price="55"/>
</Group>
<Group Price="50">
<Item Price="70"/>
<Item Price="60"/>
<Item Price="50"/>
</Group>
<!--More Group Nodes-->
</Root>
My current code is (Mix LINQ2Xml and XPATH):
'First I remove Group nodes with prices higher than 60 (and their sons).
dim filter as String="./Root/Group[not(translate(@Price, ',.', '.')<=60})]"
elements = doc.XPathSelectElements(filter).OrderByDescending((Function(x) CType(x.Attribute("Price"), Decimal)))
'Remove elements what don't fullfill the condition (prices higher than 60)
elements.Remove()
'After I remove Item nodes with prices higher than 60
filter as String="./Root/Group/Item[not(translate(@Price, ',.', '.')<=60})]"
elements = doc.XPathSelectElements(filter).OrderByDescending((Function(x) CType(x.Attribute("Price"), Decimal)))
'Remove elements what don't fullfill the condition (prices higher than 60)
elements.Remove()
As I said before, I'm filtering succesfully but I'm not able to order (descending in this case). Is there any way to order Group Nodes and Item nodes in one step or I have to do it in two steps?
Someone told me about using replaceNodes of XDocument but I don't get any results.
Thanks again for your replies.
回答1:
If you want to order the group descending then you can use LINQ and OrderByDescending.
XDocument doc = XDocument.Parse("<Root> <Group Price=\"50\"> <Item Price=\"60\"/> <Item Price=\"50\"/> <Item Price=\"70\"/> </Group> <Group Price=\"55\"> <Item Price=\"62\"/> <Item Price=\"57\"/> <Item Price=\"55\"/> </Group> <Group Price=\"61\"> <Item Price=\"62\"/> <Item Price=\"61\"/> <Item Price=\"65\"/> </Group> <!--More Group Nodes--> </Root> ");
IEnumerable<XElement> list = doc.Elements()
.Elements("Group")
.OrderByDescending(p => Convert.ToInt32(p.Attribute("Price").Value));
来源:https://stackoverflow.com/questions/11011941/order-xml-file-using-linq2xml