For speed, use an XmlReader
:
using (StringReader sr = new StringReader(myString))
using (XmlReader xr = XmlReader.Create(sr))
{
while (xr.Read())
{
if (xr.NodeType == XmlNodeType.Element && xr.Name == "foo")
{
Console.WriteLine(xr.ReadString());
}
}
}
The above prints out the text content of every element named "foo" in the XML document. (Well, sort of. ReadString
doesn't handle nested elements very gracefully.)
Using an XPathDocument
is slower, because the entire document gets parsed before you can start searching it, but it has the merit of simplicity:
using (StringReader sr = new StringReader(myString))
{
XPathDocument d = new XPathDocument(sr);
foreach (XPathNavigator n in d.CreateNavigator().Select("//foo/text()"))
{
Console.WriteLine(n.Value);
}
}
If you're not concerned with performance or memory utilization, it's simplest to use an XmlDocument
:
XmlDocument d = new XmlDocument();
d.LoadXml(myString);
foreach (XmlNode n in d.SelectNodes("//foo/text()"))
{
Console.WriteLine(n.Value);
}