.net - 使用linq2xml订购xml文件

标签 .net xpath linq-to-xml

以下问题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的信息,但没有得到任何结果。

再次感谢您的回复。

最佳答案

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

关于.net - 使用linq2xml订购xml文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11011941/

相关文章:

c# - 无法写入进程的输入

.net - web.config 授权拒绝未经授权

testing - 使用 Selenium,xpath 找不到 'text' 元素

xml - XSLT 默认替换标签值

c# - 实现动态对象从LINQ to XML select查询的捷径?

.net - 使用 XDocument 时如何在属性值中保留空格?

c# - 如何将文本框对象绑定(bind)到 ViewModel

c# - 如何使 .NET 类库可链接(无 DLL)

Python:将 dict/list/string 定义的 xml/html 元素转换为 xpath 字符串?

c# - X文档文件名