Using Linq and XDocument, can I get all the child elements under parent tag?
var accountSummaryElems =
XMLDoc.Element("summary").Elements("account");
This gives you a collection of the account
elements under the summary
element. You can then iterate them to get the values.
EDITED to use the same pattern you were; I call First()
instead of FirstOrDefault()
because that code won't run anyway if the "account" element is not found.
Then you have the right idea with iterating over the collection returned.
This returns child elements as a string list not matter where it is.
using System.Xml.Linq;
XDocument xmlDocument = XDocument.Load(fileName);
public List<string> FindChilds(string parentTag)
{
return xmlDocument.Descendants().Where(x => x.Parent != null).Where(x => x.Parent.Name.ToString().Equals(parentTag)).Select(x => x.Name.ToString()).ToList();
}
You should use the Elements
method:
var accounts = doc.Root.Elements("summary").Elements("account");
Or, alternatively, XPathSelectElements
, which in this case is simpler:
var accounts = doc.XPathSelectElements("/data/summary/account");
In this instance you can also use Descendants
, as Andrew Barber suggested, but in general you should only do this when you really want to find all descendants with a given name, and not just immediate children. Otherwise your code does a lot of searching that it doesn't need to, and may return elements you don't want it to.