Search code examples
c#xmllinq-to-xmlreadxml

C# The simplest way to obtain XML Data


I have been doing a lot of reading on LINQ to XML but unfortunately this topic (which is fairly new to me) simply will not click. Having said that, please feel free to correct any misspeaks regarding proper XML vocabulary. My goal is to take XML data, (shown below), and read it node by node. In this instance, I want to be able to open the Delimiters node, in order to obtain the values of the "one", "two", and "three" elements. Next, I would like to obtain the values of the "one", "two", and "three" elements from within the Sources/SourceType nodes.

<?xml version="1.0"?>
<Values>

  <Delimiters>
    <one>delim 1</one>
    <two>delim 2</two>
    <three>delim 3</three>
  </Delimiters>

  <Sources>

    <SourceType>
      <one>type 1</one>
      <two>type 2</two>
      <three>type 3</three>
    </SourceType>

  </Sources>

</Values>

I have read on XMLTextReader as well as XMLReader but I would like to hear from all of you what the best practices are for my situation here.

Thank you for reading,

Evan


Solution

  • You will probably want to use Linq to XML for this - parsing is straightforward:

    XDocument doc = XDocument.Load("test.xml");
    foreach (var delimiter in doc.Descendants("Delimiters").Elements())
        Console.WriteLine(string.Format("{0} : {1}", delimiter.Name, delimiter.Value));
    
    foreach (var type in doc.Descendants("SourceType").Elements())
        Console.WriteLine(string.Format("{0} : {1}", type.Name, type.Value));
    

    The big advantage of Linq to XML is that not only is it very easy to query for the nodes you want (not much difference for you example but it saves a lot in more complicated XML) but the querying syntax is ubiquitous once you become familiar with Linq in general - you don't have to change the way you think.