【问题标题】:Order xml file using linq2xml使用 linq2xml 订购 xml 文件
【发布时间】:2012-06-13 09:27:42
【问题描述】:

以下问题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()

正如我之前所说,我已成功过滤,但无法订购(在本例中为降序)。 有什么方法可以一步订购 Group Nodes 和 Item 节点,还是我必须分两步订购?

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

再次感谢您的回复。

【问题讨论】:

  • 请用简单的英语解释你想要达到的目标。您想按Price 属性值对Group 元素进行排序吗?您要删除哪些元素,Group 元素还是 Item 元素?

标签: .net xpath linq-to-xml


【解决方案1】:

如果您想对组进行降序排序,则可以使用 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));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-23
    • 2021-09-18
    • 1970-01-01
    • 2023-03-08
    • 2021-05-22
    • 1970-01-01
    • 2019-08-22
    • 1970-01-01
    相关资源
    最近更新 更多