DazzlaJ
DazzlaJ

Reputation: 57

LINQ to XML Select Nodes based on child node and attribute

I am just moving over to LINQ, so still get stuck with certain scenarios.

In the following XML I need to select the correct Persist node based on the RoomCodes attribute value and also grab need the other values from the Item/@attributes based on what we selected. So if I needed the second one I would select by the @RoomCodes = "257|1" and would also need the currency etc. from that Persist node.

Thanks All

Daz

<Root>
    <Persist>
        <Item SequenceNum="Wy4FDfktUFj"/>
        <Item RatePlanCode="Qgcu8UofK+ARXUwDD6NGf"/>
        <Item RoomCodes="232|4"/>
        <Item AmountAfterTax="1442.00"/>
        <Item CurrencyCode="USD"/>
    </Persist>
    <Persist>
        <Item SequenceNum="Wy4FDfktUFj"/>
        <Item RatePlanCode="Unk28iUoIjundujak+9094j3"/>
        <Item RoomCodes="257|1"/>
        <Item AmountAfterTax="552.00"/>
        <Item CurrencyCode="USD"/>
    </Persist>
</Root>

Upvotes: 1

Views: 1885

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236188

string value = "232|4";
var xdoc = XDocument.Load(path_to_xml);
var persist = 
    xdoc.Root.Elements("Persist")
        .FirstOrDefault(p => 
            p.Elements().Any(i => (string)i.Attribute("RoomCodes") == value));

Or with XPath extensions for LINQ to XML:

var persist = xdoc.XPathSelectElement("//Persist[Item/@RoomCodes='257|1']");

Upvotes: 2

Related Questions