ShengLong
ShengLong

Reputation: 199

Filter xml with LINQ2XML

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.

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>

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. EDIT: 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: I'd like to know if this can be done using XPATH too. I post it in another question:

Upvotes: 0

Views: 90

Answers (1)

Jeff Mercado
Jeff Mercado

Reputation: 134841

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();

Or using XPath:

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

Combined to remove groups too:

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

Upvotes: 1

Related Questions