I am using C# .
I was given an xml node from out client with child nodes as follows :
<PriceID>32</PriceID>
<Store_1> 344</Store_1>
<Store_32> 343 </Store_32>
<SS> 54</SS>
I would like to select all nodes that start with Store & SS
Is there a way I can do it ?
I know there is a way to select nodes which start with Store :
list = el.SelectNodes(@"node()[starts-with(name(), 'Store')]");
I would like to select all nodes that start with "Store" & "SS" .
Please let me know.
If you can use LINQ to XML, it's simple:
var results = doc.Descendants()
.Where(x => x.Name.LocalName.StartsWith("Store") ||
x.Name.LocalName.StartsWith("SS"));
With XmlDocument
it's harder because there's no direct equivalent of Descendants()
or DescendantsAndSelf
. You could write your own extension method:
// I'm assuming we don't mind too much about the ordering...
public static IEnumerable<XmlElement> DescendantsAndSelf(this XmlElement node)
{
return new[] { node }.Concat(node.ChildNodes
.OfType<XmlElement>()
.SelectMany(x => x.DescendantsAndSelf()));
}
Then you can use:
var results = doc.DocumentElement.DescendantsAndSelf()
.Where(x => x.LocalName.StartsWith("Store") ||
x.LocalName.StartsWith("SS"));
See more on this question at Stackoverflow