Read XML data

I am testing a free web service. http://www.webservicex.net/ws/WSDetails.aspx?CATID=2&WSID=9. I got it to return data in xml. What is the best way of reading it?

protected void Page_Load(object sender, EventArgs e)
    {
        StockQuote s = new StockQuote();
        string XmlStr = s.GetQuote("GOOG");
    }


<StockQuotes>
- <Stock>
  <Symbol>GOOG</Symbol>
  <Last>888.035</Last>
  <Date>9/24/2013</Date>
  <Time>11:34am</Time>
  <Change>+1.535</Change>
  <Open>886.50</Open>
  <High>890.10</High>
  <Low>881.40</Low>
  <Volume>652238</Volume>
  <MktCap>295.7B</MktCap>
  <PreviousClose>886.50</PreviousClose>
  <PercentageChange>+0.17%</PercentageChange>
  <AnnRange>636.00 - 928.00</AnnRange>
  <Earns>34.565</Earns>
  <P-E>25.65</P-E>
  <Name>Google Inc.</Name>
  </Stock>
  </StockQuotes>
VBdotnet2005Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

käµfm³d 👽Commented:
0
VBdotnet2005Author Commented:
Are you saying to put the returned data above into an xml file and read it that way?
0
käµfm³d 👽Commented:
You don't have to put it in a file; you can leave it in a MemoryStream if you prefer. The XmlSerializer has overloaded methods that accept Stream instances.
0
VBdotnet2005Author Commented:
I am sorry, I am very new to this. Instead of using XmlTextWriter , use XmlTextReader?
Below is your sample. Can you give me another sample

static void SerializeIt(string data, string filename)
{
    XmlSerializer serializer = new XmlSerializer(data.GetType());

    using (XmlTextWriter writer = new XmlTextWriter(filename, Encoding.UTF8))
    {
        try
        {
            serializer.Serialize(writer, data);
            Console.WriteLine("Serialization successful! Wrote test.dat!");
        }
        catch (InvalidOperationException)
        {
            Console.WriteLine("Failed to serialize object!!");
        }
    }
}
0
käµfm³d 👽Commented:
You wouldn't want this, at least at present:

data.GetType()

...because data is of type string. You want the class that represents your data. This would be a StockQuotes class. For example:

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.18052
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System.Xml.Serialization;

// 
// This source code was auto-generated by xsd, Version=4.0.30319.17929.
// 


/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class StockQuotes {
    
    private StockQuotesStock[] itemsField;
    
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("Stock", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public StockQuotesStock[] Items {
        get {
            return this.itemsField;
        }
        set {
            this.itemsField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class StockQuotesStock {
    
    private string symbolField;
    
    private string lastField;
    
    private string dateField;
    
    private string timeField;
    
    private string changeField;
    
    private string openField;
    
    private string highField;
    
    private string lowField;
    
    private string volumeField;
    
    private string mktCapField;
    
    private string previousCloseField;
    
    private string percentageChangeField;
    
    private string annRangeField;
    
    private string earnsField;
    
    private string peField;
    
    private string nameField;
    
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string Symbol {
        get {
            return this.symbolField;
        }
        set {
            this.symbolField = value;
        }
    }
    
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string Last {
        get {
            return this.lastField;
        }
        set {
            this.lastField = value;
        }
    }
    
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string Date {
        get {
            return this.dateField;
        }
        set {
            this.dateField = value;
        }
    }
    
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string Time {
        get {
            return this.timeField;
        }
        set {
            this.timeField = value;
        }
    }
    
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string Change {
        get {
            return this.changeField;
        }
        set {
            this.changeField = value;
        }
    }
    
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string Open {
        get {
            return this.openField;
        }
        set {
            this.openField = value;
        }
    }
    
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string High {
        get {
            return this.highField;
        }
        set {
            this.highField = value;
        }
    }
    
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string Low {
        get {
            return this.lowField;
        }
        set {
            this.lowField = value;
        }
    }
    
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string Volume {
        get {
            return this.volumeField;
        }
        set {
            this.volumeField = value;
        }
    }
    
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string MktCap {
        get {
            return this.mktCapField;
        }
        set {
            this.mktCapField = value;
        }
    }
    
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string PreviousClose {
        get {
            return this.previousCloseField;
        }
        set {
            this.previousCloseField = value;
        }
    }
    
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string PercentageChange {
        get {
            return this.percentageChangeField;
        }
        set {
            this.percentageChangeField = value;
        }
    }
    
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string AnnRange {
        get {
            return this.annRangeField;
        }
        set {
            this.annRangeField = value;
        }
    }
    
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string Earns {
        get {
            return this.earnsField;
        }
        set {
            this.earnsField = value;
        }
    }
    
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("P-E", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string PE {
        get {
            return this.peField;
        }
        set {
            this.peField = value;
        }
    }
    
    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public string Name {
        get {
            return this.nameField;
        }
        set {
            this.nameField = value;
        }
    }
}

Open in new window


I generated the above by using the utility xsd.exe, which you can get to via a Visual Studio Developer Command Prompt (look in the Start menu). I pasted your XML into a temp file (let's call it "temp.xml"), and then I issued the following two commands:

xsd.exe dump.xml
xsd.exe /c dump.xsd

The first command attempts to infer a schema for the XML it finds in the file. The second command generates a class file (/c) from the schema that the first command created. Now you can modify your code to:

using System.IO;
using System.Text;

...

static StockQuotes DeserializeIt(string data)
{
    XmlSerializer serializer = new XmlSerializer(typeof(StockQuotes));
    bytes[] dataBytes = Encoding.UTF8.GetBytes(data);
    MemoryStream ms = new MemoryStream(dataBytes);
    StockQuotes instance = (StockQuotes)serializer.Deserialize(ms);
    
    return instance;
}

Open in new window


Then you have access to the individual items:

e.g.

StockQuotes quotes = DeserializeIt("some data");

string symbol = quotes.Items[0].Symbol;
string lastValue = quotes.Items[0].Last;

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.