How do I load XML from local file?
Last post 05-08-2008 3:45 PM by R3DB71IND. 9 replies.
Sort Posts:
04-19-2008 9:22 PM
How do I load XML from local file?

I'm trying to do something I know has to be simple but I keep getting incomplete, outdated, or just plain wrong information. I've been researching this all day, including reading every post on this site with the words "XDocument" and still can't find a complete answer.

I'm trying to load a local, static XML file into a Silverlight app so that I can iterate through the nodes. I've tried XDocument xd = XDocument.Parse("something"); but I don't know what that "something" should be for a local file. I've also read "How To: Manipulate XML Data in Silverlight" (http://silverlight.net/QuickStarts/XmlFeatures/xmlData.aspx) but it's both out of date and pulling data from a remote location. I've also seen reference to XmlReader but don't know what to do with that information. I've also been playing with XElement but am obviously doing something wrong.

Here's what I have so far. It doesn't work but at least it doesn't crash either.

                var xe = new XElement("localFile.xml");
                var query = from item in xe.Elements()
                           select new
                           {
                               firstNode = xe.Element("firstNode").Value,
                               secondNode = xe.Element("secondNode").Value,
                               thirdNode = xe.Element("thirdNode").Value,
                               fourthNode = xe.Element("fourthNode").Value
                           };
               HtmlPage.Window.Alert(query.Count().ToString());

This returns a "0" every time. I noticed that if I change the xml file name to gibberish, it still returns 0. Any suggestions? Different approaches?

 

ap0110

Joined on 08-16-2006
Posts 9
04-20-2008 3:57 AM
Re: How do I load XML from local file?

You can do this by using OpenFileDialog.

OpenFileDialog openFileDialog1 = new OpenFileDialog();
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                // Open the selected file to read.
                System.IO.Stream fileStream =
                    openFileDialog1.SelectedFile.OpenRead();

                using (StreamReader reader = new StreamReader(fileStream))
                {
                    // Read the first line from the file and write it
                    // to the text box.
                    txt.Text = reader.ReadLine();
                }
                fileStream.Close();
            }

 

Thierry Bouquain
Ucaya
http://www.ucaya.com

thierry.bouquain

Joined on 05-06-2007
Nantes, France
Posts 224
04-21-2008 10:22 PM
Re: How do I load XML from local file?

Did you ever solve this issue? I was just trying to do something very similar and was having issues as well. Post if you find an answer! Thanks.

knorsen

Joined on 04-22-2008
Posts 5
04-21-2008 11:56 PM
Re: How do I load XML from local file?

 Thierry's solution doesn't work for you??

(If this has answered your question, please click on "Mark as Answer" on this post. Thank you!)

Best Regards,
Michael Sync

Blog : http://michaelsync.net
Feed : http://michaelsync.net/feed

mchlsync

Joined on 09-16-2005
Singapore
Posts 2,021
04-22-2008 12:12 AM
Re: How do I load XML from local file?

I suppose it could, though it seems like there would be a more graceful method to parse a local xml file (which I think was the original question). Maybe I misunderstood it though. Anyway, just wondering how one would go about this in silverlight.

Thanks. 

knorsen

Joined on 04-22-2008
Posts 5
04-22-2008 12:23 AM
Re: How do I load XML from local file?

 Actually, this may be a valid answer:

 http://silverlight.net/forums/t/14590.aspx

 

knorsen

Joined on 04-22-2008
Posts 5
04-22-2008 3:48 PM
Re: How do I load XML from local file?

knorsen:

I suppose it could, though it seems like there would be a more graceful method to parse a local xml file (which I think was the original question).

 

He's exactly right. The original question was about using a local project resource - a static xml file that's included in the project. The ultimate goal will be to post this on Silverlight Streaming. It'd be nice to be able to pull in an RSS feed but the source I want doesn't have the proper security certificate and there are just too many hassles and workarounds getting anything else to work correctly.

It seems to me that with all the XML classes (XmlDocument - which isn't included in the micro framework, XDocument, XElements, etc) that there should be a simple, elegant way to specify the source of an xml document, like XmlThing xt = new XmlThing("localfile.xml"), and then have all of the expected properties and methods available. It doesn't make sense to me that this is so complicated in SL 2. 

ap0110

Joined on 08-16-2006
Posts 9
04-22-2008 4:14 PM
Re: How do I load XML from local file?

Silverlight 2 Beta 1 doesn't allow direct access to local files since it is a security issue (remember it is running in the context of a browser). Your best bet is to use the OpenFileDialog as per the example given by Thierry.

Once you get the stream as string from the openfiledialog, you can pass that as input to XElement/XDocument, like this -

OpenFileDialog dlg = new OpenFileDialog();  
dlg.Filter = "XML Files (*.xml)|*.xml";  
if (dlg.ShowDialog() == DialogResult.OK) {  
    using (StreamReader reader = dlg.SelectedFile.OpenText()) {
        string xml = reader.ReadToEnd();
        var xe = new XElement(xml);
    }
}

Yep, a slightly roundabout way of doing things, but you could probably encapsulate the above code in a method which will simplify usage. There is no way to get past the user confirmation though (openfiledialog)

Hope this helps!

Wilfred Pinto
http://projectsilverlight.blogspot.com
 

Wilfred Pinto

Joined on 04-03-2008
Los Angeles, California, USA
Posts 143
04-22-2008 4:45 PM
Marked as Answer
Re: How do I load XML from local file?

As an experiment, here's what I cobbled together from info found in other posts on this forum and a page on Scott Gu's blog.  (My rendition could be cleaner, I know). Anyway, it works and it allows me to access the XML that is part of my test project by looking at the same location as where the silverlight is running (using a HttpWebRequest instead of just trying to open the file as a local resource). I still have a feeling there is an easier way to make this work, but I haven't run accross it yet. Code/Notes below:

 //will need to add System.Net.dll to Project References

 //inside my Page.xaml.cs

public Page()
        {

            // get the xml file

            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(new Uri(GetAppPath() + "myXmlDoc.xml"));
            request.BeginGetResponse(new AsyncCallback(ResponseCallback), request);
}


        private void ResponseCallback(IAsyncResult asyncResult)
        {
            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)asyncResult.AsyncState;
            System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.EndGetResponse(asyncResult);
            Stream content = response.GetResponseStream();

            XDocument doc = XDocument.Load(new StreamReader(response.GetResponseStream()));

            var test = from xml_test in doc.Descendants("xml_test")
                         select new
                         {
                             my_info = xml_test.Element("my_info").Value,
                         };


            foreach (var xml_test in test)
            {
                //do something with your results
            }

        }


//use to get a uri for HttpWebRequest
        public string GetAppPath()
        {
            string path = HtmlPage.Document.DocumentUri.AbsolutePath;

            path = path.Substring(0, path.LastIndexOf("/") + 1);
            return string.Concat("http://", HtmlPage.Document.DocumentUri.Host, ":", HtmlPage.Document.DocumentUri.Port, path);

        }

knorsen

Joined on 04-22-2008
Posts 5
05-08-2008 3:45 PM
Re: How do I load XML from local file?

Knorsen- that worked well for me. Thanks!

To any n00bs (like myself)  that may be following this you will need these to run knorsen's code:

using System.Net;
using System.IO;
using System.Windows.Browser;

J Cip
Interactive Developer

R3DB71IND

Joined on 05-08-2008
Posts 1