How do I read an XML File?

  • (2 Pages)
  • +
  • 1
  • 2

19 Replies - 810 Views - Last Post: 22 August 2018 - 06:14 PM Rate Topic: ***-- 2 Votes

#1 Braber01   User is offline

  • D.I.C Regular

Reputation: 5
  • View blog
  • Posts: 331
  • Joined: 29-November 08

How do I read an XML File?

Posted 19 August 2018 - 12:44 PM

I have a movie rental Application and I'm having trouble reading a webresponse

here is my code so far
using System;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Net;
using System.IO;

namespace MovieStoreApp
{
  public partial class Form2 : Form
  {
    public Form2()
    {
      InitializeComponent();
    }

    private void btnSearch_Click(object sender, EventArgs e)
    {
      StringBuilder requestURL = new StringBuilder();
      string apiKey = "apikey=someApiKey"; //not really the key
      string title = txtSearch.Text;
      string titleQuery = title.Replace(" ","+");
      string type;
      requestURL.Append("www.omdbapi.com/?");
      requestURL.Append(apiKey);
      requestURL.Append("&t=" + titleQuery);
      if(radMovie.Checked)
      {
        type="movie";
        requestURL.Append("&type={0}",type);
      }
      else if (radSeries.Checked)
      {
        type="series";
        requestURL.Append("&type={0}",type);
      }
      else if(radEpsiode.Checked)
      {
        type="episode";
        requestURL.Append("&type={0}",type);
      }
      else
      {
         //append nothing
      }
      string plot;
      if (radShort.Checked)
      {
         plot = "short";
         requestURL.Append("&plot={0}",plot);
      }
      else if(radFull.Checked)
      {
        plot="full";
        requestURL.Append("&plot={0}",plot);
      }
      else
      {
      }
      requestURL.Append("&r=xml");
      WebRequest request = WebRequest.Create(requestURL.ToString());
      request.Credentials = CredentialCache.DefaultCredentials;
      
     using (WebResponse = request.GetResponse())
     using (Stream responseStream = response.GetResponseStream())
     {
       if(Flie.Exists("response.xml")
       {
         File.Delete("response.xml");
       }
       using(FileStream output = File.Create("response.xml"))
       {
          Copy(responseStream, output);
       }
     }
   }
   public void Copy(Stream input, Stream output)
   {
     const int BUFFER_SIZE = 8192;
     byte[] buffer = new byte[BUFFER_SIZE];
     int read;
     while ((read = input.Read(buffer,0,buffer.Length)) > 0)
     {
       output.Write(buffer,0,read);
     }
  }
  public byte[] ReadFully(Stream input)
  {
    using (MemoryStream tempStream = new MemoryStream())
    {
      Copy(input,tempStream);
      if(tempStream.Length == tempStream.GetBuffer().Length)
      {
        return tempStream.GetBuffer();
      }
      return tempStream.ToArray();
    }
    private void btnReadXML_Click(object sender,EventArgs e)
    {
       XmlDocument xmlDocument = new XmlDocument();
       xmldocument.Load("response.xml");
       XmlReader reader; //And I'm stuck here.
   }
  }
}



Is This A Good Question/Topic? 0
  • +

Replies To: How do I read an XML File?

#2 Martyr2   User is offline

  • Programming Theoretician
  • member icon

Reputation: 5283
  • View blog
  • Posts: 14,105
  • Joined: 18-April 07

Re: How do I read an XML File?

Posted 19 August 2018 - 01:08 PM

Have you tried searching for an example of xmldocument?

https://docs.microso...framework-4.7.2

Here it shows you how to create, read, navigate children etc. All you really need to work with XmlDocument and its methods. :)
Was This Post Helpful? 0
  • +
  • -

#3 Sheepings   User is offline

  • Senior Programmer
  • member icon

Reputation: 95
  • View blog
  • Posts: 697
  • Joined: 05-December 13

Re: How do I read an XML File?

Posted 19 August 2018 - 01:34 PM

View PostBraber01, on 19 August 2018 - 08:44 PM, said:

I have a movie rental Application and I'm having trouble reading a webresponse

here is my code so far
065
     using (Stream responseStream = response.GetResponseStream())
066
     {
067
       if(Flie.Exists("response.xml")
068
       {
069
         File.Delete("response.xml");
070
       }
071
       using(FileStream output = File.Create("response.xml"))
072
       {
073
          Copy(responseStream, output);
074
       }
075
     }



I would politely advise you do a little more research into the code you are using. Its bad practice to delete files and recreate them in the same instance. Generally, I use functions for these implemented actions.

It's even worse that you're not wrapping your code in Try Catch Blocks to catch the likely IOException you may occasionally experience. You should also check if the file is in use, before trying to delete it, as this will likely throw an exception error at some point.

I'm not seen the relation between reading a web response, and your problem with a xml file? Can you explain what your problem is, and what the desired expectations are and where in your code, you're having issues or experiencing errors?
Was This Post Helpful? 0
  • +
  • -

#4 Braber01   User is offline

  • D.I.C Regular

Reputation: 5
  • View blog
  • Posts: 331
  • Joined: 29-November 08

Re: How do I read an XML File?

Posted 21 August 2018 - 09:33 AM

I end up getting the webresponse as xml, I'm not really experencing any errors or anything I'm just stuck as to where to go, is it possible just to read the response that comes back as xml with out having to save it to a file?
Was This Post Helpful? 0
  • +
  • -

#5 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 6404
  • View blog
  • Posts: 21,972
  • Joined: 05-May 12

Re: How do I read an XML File?

Posted 21 August 2018 - 09:34 AM

Yes. What makes you think that you need to save it to a file?
Was This Post Helpful? 0
  • +
  • -

#6 astonecipher   User is offline

  • Senior Systems Engineer
  • member icon

Reputation: 2654
  • View blog
  • Posts: 10,584
  • Joined: 03-December 12

Re: How do I read an XML File?

Posted 21 August 2018 - 09:59 AM

I do this daily, because we use XML as our content type.
private IHttpActionResult GetItems(XmlDocument xmlDoc)
        {
            xmlDoc.SelectSingleNode("//SecurityToken").InnerText = token;


Example
Was This Post Helpful? 1
  • +
  • -

#7 Sheepings   User is offline

  • Senior Programmer
  • member icon

Reputation: 95
  • View blog
  • Posts: 697
  • Joined: 05-December 13

Re: How do I read an XML File?

Posted 21 August 2018 - 11:48 AM

View PostBraber01, on 21 August 2018 - 05:33 PM, said:

I end up getting the webresponse as xml, I'm not really experencing any errors or anything I'm just stuck as to where to go, is it possible just to read the response that comes back as xml with out having to save it to a file?

You don't need to save it to a file. When you receive it, you do what you want with it. There might be a simpler way to do what you want. What is it that your webresponse is meant to receive? And what is the URL that it is getting the response from?
Was This Post Helpful? 0
  • +
  • -

#8 Braber01   User is offline

  • D.I.C Regular

Reputation: 5
  • View blog
  • Posts: 331
  • Joined: 29-November 08

Re: How do I read an XML File?

Posted 21 August 2018 - 02:27 PM

I need to get the Attributes of the Movie element and the uri I'm using to test it www.omdbapi.com?apikey=d9341b90&t=Gone+With+The+Wind&r=xml the response/uri should get an xml document containing the data for the Movie "Gone Wtih the Wind" and I need to read the attributes in the "root/movie" element.
Was This Post Helpful? 0
  • +
  • -

#9 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 6404
  • View blog
  • Posts: 21,972
  • Joined: 05-May 12

Re: How do I read an XML File?

Posted 21 August 2018 - 07:05 PM

See Xmldocument.Load(Stream)
Or Xdocument.Load(Stream)
Was This Post Helpful? 0
  • +
  • -

#10 Sheepings   User is offline

  • Senior Programmer
  • member icon

Reputation: 95
  • View blog
  • Posts: 697
  • Joined: 05-December 13

Re: How do I read an XML File?

Posted 22 August 2018 - 05:43 AM

Let me know if this works for you @Braber01.

Attached Image

private void button2_Click(object sender, EventArgs e)
        {
            try
            {   //Method one LinQ
                //var xDoc = XElement.Load("http://www.omdbapi.com/?apikey=d9341b90&t=Gone+With+The+Wind&r=xml");
                //var xAttributes = xDoc.Descendants()
                //                 .SelectMany(x => x.Attributes())
                //                 .ToDictionary(x => x.Name.LocalName, x =>
                //                 listBox1.Items.Add((string)x));
                //Method two (My Preferred Method)
                XmlDocument xDoc = new XmlDocument(); //Lets declare

                xDoc.Load("http://www.omdbapi.com/?apikey=d9341b90&t=Gone+With+The+Wind&r=xml"); //Load your XML file

                //NOTE: I looked at your original code, and I seen that you concatenate the strings to include the
                //API etc, which I didn't do here, so If you are going to string build your XML url, I suggest you
                //do it under the "Lets Declare section, and don't change the declaration name of XDoc.

                List<string> eAttributes = new List<string>();//Lets create a list to add the items too.
                //Might be handy for you to iterate later, should you need...

                List<XmlNode> nNodes = new List<XmlNode>();
                XmlNode myNode = xDoc.FirstChild;//Lets go get the node and loop through each attribute
                foreach (XmlElement n in myNode.NextSibling)
                {
                    XmlAttributeCollection xAttributes = n.Attributes;
                    foreach (XmlAttribute eAttrib in xAttributes)
                    {
                        if (eAttrib.LocalName != null & eAttrib.LocalName == ("title"))
                        {
                            Console.WriteLine("Title: " + eAttrib.Value);
                            eAttributes.Add(eAttrib.Value);
                        }
                        else if (eAttrib.LocalName != null & eAttrib.LocalName == ("year"))
                        {
                            Console.WriteLine("Year: " + eAttrib.Value);
                            eAttributes.Add(eAttrib.Value);
                        }
                        else if (eAttrib.LocalName != null & eAttrib.LocalName == ("rated"))
                        {
                            Console.WriteLine("Rated: " + eAttrib.Value);
                            eAttributes.Add(eAttrib.Value);
                        }
                        else if (eAttrib.LocalName != null & eAttrib.LocalName == ("released"))
                        {
                            Console.WriteLine("Released: " + eAttrib.Value);
                            eAttributes.Add(eAttrib.Value);
                        }
                        else if (eAttrib.LocalName != null & eAttrib.LocalName == ("runtime"))
                        {
                            Console.WriteLine("Runtime: " + eAttrib.Value);
                            eAttributes.Add(eAttrib.Value);
                        }
                        else if (eAttrib.LocalName != null & eAttrib.LocalName == ("genre"))
                        {
                            Console.WriteLine("Genre: " + eAttrib.Value);
                            eAttributes.Add(eAttrib.Value);
                        }
                        else if (eAttrib.LocalName != null & eAttrib.LocalName == ("director"))
                        {
                            Console.WriteLine("Directors: " + eAttrib.Value);
                            eAttributes.Add(eAttrib.Value);
                        }
                        else if (eAttrib.LocalName != null & eAttrib.LocalName == ("writer"))
                        {
                            Console.WriteLine("Writer: " + eAttrib.Value);
                            eAttributes.Add(eAttrib.Value);
                        }
                        else if (eAttrib.LocalName != null & eAttrib.LocalName == ("actors"))
                        {
                            Console.WriteLine("Actors: " + eAttrib.Value);
                            eAttributes.Add(eAttrib.Value);
                        }
                        else if (eAttrib.LocalName != null & eAttrib.LocalName == ("plot"))
                        {
                            Console.WriteLine("Plot: " + eAttrib.Value);
                            eAttributes.Add(eAttrib.Value);
                        }
                        else if (eAttrib.LocalName != null & eAttrib.LocalName == ("language"))
                        {
                            Console.WriteLine("Language: " + eAttrib.Value);
                            eAttributes.Add(eAttrib.Value);
                        }
                        else if (eAttrib.LocalName != null & eAttrib.LocalName == ("country"))
                        {
                            Console.WriteLine("Country: " + eAttrib.Value);
                            eAttributes.Add(eAttrib.Value);
                        }
                        else if (eAttrib.LocalName != null & eAttrib.LocalName == ("awards"))
                        {
                            Console.WriteLine("Awards: " + eAttrib.Value);
                            eAttributes.Add(eAttrib.Value);
                        }
                        else if (eAttrib.LocalName != null & eAttrib.LocalName == ("metascore"))
                        {
                            Console.WriteLine("MetaScore: " + eAttrib.Value);
                            eAttributes.Add(eAttrib.Value);
                        }
                        else if (eAttrib.LocalName != null & eAttrib.LocalName == ("imdbRating"))
                        {
                            Console.WriteLine("IMDB Rating: " + eAttrib.Value);
                            eAttributes.Add(eAttrib.Value);
                        }
                        else if (eAttrib.LocalName != null & eAttrib.LocalName == ("imdbvotes"))
                        {
                            Console.WriteLine("IMDB Votes: " + eAttrib.Value);
                            eAttributes.Add(eAttrib.Value);
                        }
                        else if (eAttrib.LocalName != null & eAttrib.LocalName == ("imdbID"))
                        {
                            Console.WriteLine("IMDB ID: " + eAttrib.Value);
                            eAttributes.Add(eAttrib.Value);
                        }
                        else if (eAttrib.LocalName != null & eAttrib.LocalName == ("type"))
                        {
                            Console.WriteLine("Type: " + eAttrib.Value);
                            eAttributes.Add(eAttrib.Value);
                        }
                        else if (eAttrib.LocalName != null & eAttrib.LocalName == ("poster"))
                        {//I assume you will want to use this with a picturebox on your app?
                            Console.WriteLine("Poster URL: " + eAttrib.Value);
                            eAttributes.Add(eAttrib.Value);
                            pictureBox1.SizeMode = PictureBoxSizeMode.Zoom; //Set it to Zoom so the image fits the size of the picturebox
                            pictureBox1.Load(eAttrib.Value); //Load in the image to the picture box
                        }
                    }
                }
            }
            catch (NullReferenceException nException)
            {
                Console.WriteLine(nException.TargetSite);
                //Handle your null ref here if any
            }
        }

Was This Post Helpful? 3
  • +
  • -

#11 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 6404
  • View blog
  • Posts: 21,972
  • Joined: 05-May 12

Re: How do I read an XML File?

Posted 22 August 2018 - 06:48 AM

+1 for Method 1.
Was This Post Helpful? 0
  • +
  • -

#12 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 6404
  • View blog
  • Posts: 21,972
  • Joined: 05-May 12

Re: How do I read an XML File?

Posted 22 August 2018 - 07:02 AM

In method 2, in C# beware of using the bitwise & when you really mean the logical &&.

Also the following:
eAttrib.LocalName != null & eAttrib.LocalName == ("title")


can be simplified to
eAttrib.LocalName == "title"


because it never be null if it is equal to some string value.
Was This Post Helpful? 1
  • +
  • -

#13 Sheepings   User is offline

  • Senior Programmer
  • member icon

Reputation: 95
  • View blog
  • Posts: 697
  • Joined: 05-December 13

Re: How do I read an XML File?

Posted 22 August 2018 - 07:22 AM

Good spot for the short-circuit evaluation on my end. But it's a simple adjustment for the OP. In fact, I was meant to remove the null check as I was only initially testing evaluation of one side of the statement anyway, and from there, copy/pasted the code for the elseif.

Thanks

This post has been edited by Skydiver: 22 August 2018 - 08:15 AM
Reason for edit:: Removed unnecessary quote. No need to quote the post above yours.

Was This Post Helpful? 0
  • +
  • -

#14 Braber01   User is offline

  • D.I.C Regular

Reputation: 5
  • View blog
  • Posts: 331
  • Joined: 29-November 08

Re: How do I read an XML File?

Posted 22 August 2018 - 01:53 PM

The method is just about perfect, I also want to get the name of the attribuates so I have the Rating show something like Rating: G etc.
Was This Post Helpful? 0
  • +
  • -

#15 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 6404
  • View blog
  • Posts: 21,972
  • Joined: 05-May 12

Re: How do I read an XML File?

Posted 22 August 2018 - 01:56 PM

If you are just after the rating, then use SelectSingleNode(). There is no point iterating over all the nodes if you are only interested in one item.
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2