I am trying to pull multiple elements out of an XML documents and their children but I cannot find a useful example anywhere... MSDN is very vague. This is c# in .Net
I am creating this XML dynamically already and transferring it to a string. I have been trying to use XmlNode with a NodeList to go through each file in a foreach section but It is not working properly.
Here is some sample XML:
<searchdoc>
<results>
<result no = "1">
<url>a.com</url>
<lastmodified>1/1/1</lastmodified>
<description>desc1</description>
<title>title1</title>
</result>
<result no = "2">
<url>b.com</url>
<lastmodified>2/2/2/</lastmodified>
<description>desc2</description>
<title>title2</title>
</result>
</results>
</searchdoc>
I need to pull each of the full paths <result>
If your document is not too big (I think it's not, as you're already generating it dinamically), couldn't you simply use LINQ to Xml?
XDocument myDoc = XDocument.Parse(myXmlString);
foreach(var result in myDoc.Descendants("result"))
{
DoStuffWithTitle(result.Element("Title").Value);
...
}
There are multiple ways to solve this problem, depending on which version of the .NET Framework you are working on:
You can easily obtain a filtered list of nodes from your XML document by issuing an XPath query via the XPathDocument class:
using (var reader = new StringReader("<Results><Result>...</Result></Results>"))
{
var document = new XPathDocument(reader);
var navigator = document.CreateNavigator();
var results = navigator.Select("//result");
while (results.MoveNext())
{
Console.WriteLine("{0}:{1}", results.Current.Name, results.Current.Value);
}
}
You should use LINQ to XML to query and filter XML hierarchies, since it offers a much more expressive API than the XPath syntax:
var document = XDocument.Parse("<Results><Result>...</Result></Results>");
var results = document.Elements("result");
foreach (var item in results)
{
Console.WriteLine("{0}:{1}", item.Name, item.Value);
}
Related resources:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With