1

I'm trying to select multiple nodes in one query.

My XML looks like

<View Id="View#1">
    <Node1 DefinitionId="DefinitionId1">
        // ...
    </Node1>
</View>
<View Id="View#2">
    <Node2 DefinitionId="DefinitionId2">
        // ...
    </Node2>
</View>
<View Id="View#3">
    <Node3 DefinitionId="DefinitionId3">
        // ...
    </Node3>
</View>

I'm currently have the XML document loaded through XDocument.Load and I am parsing the resultant XML through LINQ to XML.

I'm basically trying to get all of the definition id's of all the node types into a single string collection.

My current code looks like this

IList<string> node1Ids = _xmlFile
    .Descendants("Node1")
    .Select(n => n.Attribute("DefinitionId").Value).ToList();

IList<string> node2Ids = _xmlFile
    .Descendants("Node2")
    .Select(n => n.Attribute("DefinitionId").Value).ToList();

Is there any way of putting all of this into one query such as

IList<string> nodeIds = _xmlFile
    .Descendants("Node1")
    .Descendants("Node2")
    .Descendants("Node3")
    .Select(n => n.Attribute("DefinitionId").Value).ToList();

Obviously the above does not work but I'm wondering if there is an equivalent to allow me to do the same thing.

2 Answers 2

2

You could try _xmlFile.Descendants("View").Elements().Attributes("DefinitionId").Select(a => a.Value).ToList(). That assumes that you are looking for the DefinitionId attributes of all child elements of all View elements. Or you need something like Descendants().Where(d => d.Name.LocalName.StartsWith("Node")).Attributes("DefinitionId").Select(a => a.Value).ToList().

Sign up to request clarification or add additional context in comments.

Comments

1

You may try below:

IList<string> nodeIds = _xmlFile
    .Descendants().Where( d => d.Name.LocalName.StartsWith("Node") )
    .Select(n => n.Attribute("DefinitionId").Value).ToList();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.