Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get a specific example of XML in c#

Tags:

c#

.net

xml

xslt

xpath

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>

like image 962
Christopher Avatar asked Apr 25 '11 20:04

Christopher


2 Answers

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);
  ...
}
like image 29
LazyOfT Avatar answered Sep 22 '22 18:09

LazyOfT


There are multiple ways to solve this problem, depending on which version of the .NET Framework you are working on:

.NET 1.x, 2.0 and 3.0

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);
  }
}

.NET 3.5 and later

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:

  • How to query XML with an XPath expression by using Visual C#
  • LINQ to XML Overview
  • Comparison of XPath and LINQ to XML
like image 123
Enrico Campidoglio Avatar answered Sep 23 '22 18:09

Enrico Campidoglio