2

以下问题Filter xml with LINQ2XML

从 xml 文件中成功过滤(删除节点)后。我想按节点中的某些属性排序。

xml文件示例:

<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> 

我想得到:

<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>

我当前的代码是(混合 LINQ2Xml 和 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()

正如我之前所说,我过滤成功但我无法订购(在这种情况下下降)。有没有办法一步订购组节点和项目节点,或者我必须分两步完成?

有人告诉我使用 XDocument 的 replaceNodes,但我没有得到任何结果。

再次感谢您的回复。

4

1 回答 1

0

如果要对组进行降序排序,则可以使用 LINQ 和 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));
于 2012-06-15T02:05:20.533 回答