Reputation: 173
Is it possible to use LINQ to extract child elements from a parent element, for example:
XML
<?xml version="1.0"?>
<Names>
<Harrison>
<preName>Simon</preName>
<preName>John</preName>
</Harrison>
<Smith>
<preName>Harvey</preName>
<preName>Oscar</preName>
</Smith>
</Names>
VB.NET
private sub query()
Dim file as string = "C:\SomexmlFile.xml"
Dim query = From Names In File
Where Names = Harrison
Select preName
end sub
Would something like that work? Is there any syntax that would select all the preNames of that child element, like MySql "Select * FROM file WHERE Name = Harrison" (I know that wouldn't work as MySql wont query xml but you get my meaning)
TIA
Upvotes: 0
Views: 959
Reputation: 101042
Sure:
Dim xml = <Names>
<Harrison>
<preName>Simon</preName>
<preName>John</preName>
</Harrison>
<Smith>
<preName>Harvey</preName>
<preName>Oscar</preName>
</Smith>
</Names>
Dim harrisons = from prename in xml.<Harrison>
from name in prename.<preName>
select name.Value
harrisons
now contains Simon
and John
.
Another way:
xml.Elements.First(function(e) e.Name = "Harrison").Elements _
.Select(function(h) h.Value)
or simply using XPath:
xml.XPathSelectElements("Harrison/preName").Select(Function(n) n.Value)
Upvotes: 1