使用LINQ2XML过滤xml [英] Filter xml with LINQ2XML

查看:137
本文介绍了使用LINQ2XML过滤xml的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是LINQ2XML的新手.我正在尝试过滤一个xml文件并使用结果获取另一个xml.我想按某些属性的值进行过滤.

I'm a newbie with LINQ2XML. I'm trying to filter an xml file and get another xml with the results. I want to filter by the value of some attributes.

xml看起来像这样(缩写版,实际版本具有更多的节点和属性):

The xml looks like this (abreviated version, the actual version has more nodes and attributes):

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

现在让我们假设我想要价格低于60的节点.我想要得到的是: 我已经删除了价格分别为60、70和62的节点.我想删除价格为61的组节点(它没有满足条件).

Now let's suppose I want nodes with value whose price is lower than 60. What I want to get is: I've removed nodes with prices 60, 70 and 62. I want to remove Group Node with price 61 (it doesn't fullfill the condition).

<Root>
    <Group Price="50">
       <Item Price="50"/>
    </Group>
    <Group Price="55">
       <Item Price="57"/>
       <Item Price="55"/>
    </Group>
    <!--More Group Nodes--> 
</Root>

或者也许有什么方法可以删除那些不能满足条件的节点?感谢您的回答.

Or maybe is there any way to remove nodes what don't fullfill the conditions? Thanks for your answers.

PS:我想知道是否也可以使用XPATH完成此操作.我将其发布在另一个问题中:

PS: I'd like to know if this can be done using XPATH too. I post it in another question:

推荐答案

搜索要删除的节点,然后将其删除.

Search for the nodes to remove then remove them.

var filterPrice = 60M;
var removeMe =
    from item in doc.Descendants("Item")
    where (decimal)item.Attribute("Price") >= filterPrice
    select item;
removeMe.Remove();

或使用XPath:

var filterPrice = 60M;
var xpath = String.Format("//Item[@Price>={0}]", filterPrice);
var removeMe = doc.XPathSelectElements(xpath);
removeMe.Remove();

也可以组合删除组:

var filterItemPrice = 60M;
var filterGroupPrice = 60M;
var removeGroups =
    from grp in doc.Descendants("Group")
    where (decimal)grp.Attribute("Price") >= filterGroupPrice
    select grp;
var removeItems =
    from item in doc.Descendants("Item")
    where (decimal)item.Attribute("Price") >= filterItemPrice
    select item;
var removeMe = removeItems.Concat(removeGroups);

这篇关于使用LINQ2XML过滤xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆