• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 713
  • Last Modified:

How to read a xml file in C#

I need to read an xml file that has the following lines:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfSplitBase xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <SplitBase Exchange="NYSE" Symbol="HEI" DateTime="2011-04-26T00:00:00" Ratio="5-4" />
  <SplitBase Exchange="NYSE" Symbol="EEQ" DateTime="2011-04-25T00:00:00" Ratio="2-1" />
  <SplitBase Exchange="NYSE" Symbol="EEP" DateTime="2011-04-25T00:00:00" Ratio="2-1" />
  <SplitBase Exchange="NYSE" Symbol="SF" DateTime="2011-04-06T00:00:00" Ratio="3-2" />

I can open the file in C#.

        // Create an instance of XmlTextReader and call Read method to read the file

        XmlTextReader textReader = new XmlTextReader(@pstrSourceFile);

        textReader.Read();

        // If the node has value

        while (textReader.Read())
        {
              Write the SplitBase Exchange value ("NYSE") into string1
            // Move to first element

What is the syntax for reading each element into variables?

                     Write the SplitBase Exchange value ("NYSE") into string1
                     Write the Symbol value("HEI") into string2
                     etc.    

The examples I found refer to books.xml

Where can I find books.xml for downloading?

Thanks,



0
Dovberman
Asked:
Dovberman
4 Solutions
 
Gerwin Jansen, EE MVETopic Advisor Commented:
0
 
mrjoltcolaCommented:
Simpler method:
  using System.Xml;

  // Load file to XML doc
  var doc = new XmlDocument();
  doc.Load("myfile.xml");


Now you do what you want with it:

  XmlNode splitBases = doc.SelectNodes("//*local-name()='SplitBase']");
  foreach(var n in splitBases.OfType<XmlElement>()) {
      var exchAttr = n.Attributes["Exchange"];
      var symbAttr = n.Attributes["Symbol"];
      // etc...
      Console.WriteLine(exchAttr.Value);
  }
0
 
DovbermanAuthor Commented:
OK
I need help with the terminology.

<?xml version="1.0" encoding="utf-8"?>  Is this the root node? if so, where is the closing node?
<ArrayOfSplitBase xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <SplitBase Exchange="NYSE" Symbol="HEI" DateTime="2011-04-26T00:00:00" Ratio="5-4" />
  <SplitBase Exchange="NYSE" Symbol="EEQ" DateTime="2011-04-25T00:00:00" Ratio="2-1" />
  <SplitBase Exchange="NYSE" Symbol="EEP" DateTime="2011-04-25T00:00:00" Ratio="2-1" />
  <SplitBase Exchange="NYSE" Symbol="SF" DateTime="2011-04-06T00:00:00" Ratio="3-2" />
</ArrayOfSplitBase>

I guess that I need to move to each line.

SplitBase Exchange="NYSE" Symbol="EEP" DateTime="2011-04-25T00:00:00" Ratio="2-1"

Is the content of a line
If this is true, then I need to parse the line for
   "SplitBase Exchange=" and read the text that follows
   "Symbol=" and read the text that follows
Hopefully, you can help me with syntax for this specific file.

Thanks,

   
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
anarki_jimbelCommented:
"<?xml version="1.0" encoding="utf-8"?>  Is this the root node? if so, where is the closing node?"

No, this is xml declaration. Basicly, it's same for all xml documents. You don't really need it.

The root element is "ArrayOfSplitBase".

SplitBase - are xml elements.

Exchange, DateTime - are attributes for the element.

SplitBase  element has no text or any other content.
0
 
anarki_jimbelCommented:
Try the following code below. XmlDocument class does all parsing for you. I believe you need to access information from your xml elements. See how this can be achieved, with some comments in code.

The output is:
SplitBase1:  
      Exchange=NYSE
      Exchange=HEI
      Exchange=2011-04-26T00:00:00
      Exchange=5-4

SplitBase2:  
      Exchange=NYSE
      Exchange=EEQ
      Exchange=2011-04-25T00:00:00
      Exchange=2-1

SplitBase3:  
      Exchange=NYSE
      Exchange=EEP
      Exchange=2011-04-25T00:00:00
      Exchange=2-1

SplitBase4:  
      Exchange=NYSE
      Exchange=SF
      Exchange=2011-04-06T00:00:00
      Exchange=3-2
private void button1_Click(object sender, EventArgs e)
        {
            //Read xml file to the object
            XmlDocument doc = new XmlDocument();
            doc.Load("XMLFile1.xml");

           // string namespaces = doc.
           XmlNodeList nodes =  doc.SelectNodes("//SplitBase");
            // we have 4 elements in the example and we may check their content:
            int counter = 0;
           foreach (XmlNode node in nodes)
           {
               counter++;
               // print our each element with it's attributes and their values: 
               XmlElement ele = (XmlElement)node;
               XmlAttribute at1 = (XmlAttribute)node.Attributes.GetNamedItem("Exchange");
               XmlAttribute at2 = (XmlAttribute)node.Attributes.GetNamedItem("Symbol");
               XmlAttribute at3 = (XmlAttribute)node.Attributes.GetNamedItem("DateTime");
               XmlAttribute at4 = (XmlAttribute)node.Attributes.GetNamedItem("Ratio");
               System.Diagnostics.Debug.WriteLine(node.Name + counter+ ":  " + Environment.NewLine + 
                   "\t" + at1.Name + "=" + at1.Value +Environment.NewLine + 
                   "\t" + at1.Name + "=" + at2.Value +Environment.NewLine + 
                   "\t" + at1.Name + "=" + at3.Value +Environment.NewLine + 
                   "\t" + at1.Name + "=" + at4.Value +Environment.NewLine );
                                                                                        

           }

Open in new window

0
 
anarki_jimbelCommented:
Or a bit modified. It's not much different from mrjoltcola's but bit more clear...
private void button1_Click(object sender, EventArgs e)
        {
            //Read xml file to the object
            XmlDocument doc = new XmlDocument();
            doc.Load("XMLFile1.xml");

           // we aren't really interested in the root element here. Look for content elements
           XmlNodeList nodes =  doc.SelectNodes("//SplitBase");
            // we have 4 elements in the example and we may check their content:
            int counter = 0;
           foreach (XmlNode node in nodes)
           {
               counter++;
               // print our each element with it's attributes and their values: 
               XmlElement ele = (XmlElement)node;
               XmlAttribute at1 = node.Attributes["Exchange"];
               XmlAttribute at2 = node.Attributes["Symbol"];
               XmlAttribute at3 = node.Attributes["DateTime"];
               XmlAttribute at4 = node.Attributes["Ratio"];
               System.Diagnostics.Debug.WriteLine(node.Name + counter+ ":  " + Environment.NewLine + 
                   "\t" + at1.Name + "=" + at1.Value +Environment.NewLine + 
                   "\t" + at1.Name + "=" + at2.Value +Environment.NewLine + 
                   "\t" + at1.Name + "=" + at3.Value +Environment.NewLine + 
                   "\t" + at1.Name + "=" + at4.Value +Environment.NewLine );
                                                                                        

           }

Open in new window

0
 
DovbermanAuthor Commented:
anarki_jimbel:
 I do not want to writeline.

I need to set the line content into a variable.

string strExchange=" ";
string strSymbol = " ";
foreach (XmlNode node in nodes)
           {
               counter++;
               // print our each element with it's attributes and their values:
               XmlElement ele = (XmlElement)node;
               XmlAttribute at1 = node.Attributes["Exchange"];
               XmlAttribute at2 = node.Attributes["Symbol"];
               XmlAttribute at3 = node.Attributes["DateTime"];
               XmlAttribute at4 = node.Attributes["Ratio"];
              // Set the Exchange value into strExchange

strExchange = ?
Should return "NYSE"
strSymbol = ?
Should return "HEI"

Why is it so complicated to simply read the content of a line into a string ? If I can do this, I can parse the string for the values of Exchange, Symbol, etc.

ie
strLineContent = ?
strLineContent = SplitBase Exchange="NYSE" Symbol="HEI" DateTime="2011-04-26T00:00:00" Ratio="5-4"

0
 
oxyooCommented:
Hi, here is another approach using Linq2Xml. I myself find it more easily to use. Hopefully this is what you want. I have extracted all SplitBase xml data into objects of the custom type SplitBase which I've created. You can then access all properties and do what you want with them. I found it to be easier to move objects around rather than having lots of strings.

Hope that helps.


namespace EE {
  using System;
  using System.Collections.Generic;
  using System.IO;
  using System.Linq;
  using System.Xml;
  using System.Xml.Linq;

  public class HowToReadXmlFileInCSharp {
    public IEnumerable<SplitBase> GetAllSplitBases(string path) {
      var document = XDocument.Load(new XmlTextReader(path));
      var splitbases = from content in document.Descendants("SplitBase") 
                     select new SplitBase { 
                           Exchange = content.Attribute("Exchange").Value, 
                           DateTime = DateTime.Parse(content.Attribute("DateTime").Value), 
                           Ratio = content.Attribute("Ratio").Value, 
                           Symbol = content.Attribute("Symbol").Value
                     };

      return splitbases;
    }
  }

  public class SplitBase {
    public string Exchange { get; set; }
    public string Symbol { get; set; }
    public DateTime DateTime { get; set; }
    public string Ratio { get; set; }

    public override string ToString() {
      return string.Format("{0} | {1} | {2} | {3}", Exchange, Symbol, DateTime, Ratio);
    }
  }
}

Open in new window

<?xml version="1.0" encoding="utf-8" ?>
<ArrayOfSplitBase xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <SplitBase Exchange="NYSE" Symbol="HEI" DateTime="2011-04-26T00:00:00" Ratio="5-4" />
  <SplitBase Exchange="NYSE" Symbol="EEQ" DateTime="2011-04-25T00:00:00" Ratio="2-1" />
  <SplitBase Exchange="NYSE" Symbol="EEP" DateTime="2011-04-25T00:00:00" Ratio="2-1" />
  <SplitBase Exchange="NYSE" Symbol="SF" DateTime="2011-04-06T00:00:00" Ratio="3-2" />
</ArrayOfSplitBase>

Open in new window

namespace EE {
    using System;

    internal class Program {
        private static void Main(string[] args) {
            var splitbases = new HowToReadXmlFileInCSharp().GetAllSplitBases("HowToReadXmlFileInCSharp.xml");
            foreach (var splitBase in splitbases) { Console.WriteLine(splitBase);}
            
        }
    }
}

Open in new window

0
 
DovbermanAuthor Commented:
oxyoo:

This makes sense.

I will try it tomorrow.

Thanks,
0
 
DovbermanAuthor Commented:
I found a tab delimited text file. I no longer need to read an xml file.

Thanks fo all your help.
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now