bswee
bswee

Reputation: 81

How can I correct the code to read a xml file?

This code works as it is but when I reference an external xml file in doc.Loadxml, it stops working. How can I get it to work? I don't quite understand.

I use this to call GetXmlData and provide source for the gridview :GridView1.ItemsSource = GetXmlData();

   private static object GetXmlData()
    {
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(@"<?xml version=""1.0"" encoding=""utf-8"" ?>
        <Products>
          <Product>
            <ID>1</ID>
            <Name>ASP.NET</Name>
          </Product>
        </Products>
         ");

        XmlDataProvider provider = new XmlDataProvider();
        provider.IsAsynchronous = false;
        provider.Document = doc;
        provider.XPath = "Products/Product";

        return new ObservableCollection<XmlNode>((IEnumerable<XmlNode>)provider.Data);
    }

Upvotes: 0

Views: 126

Answers (3)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361812

XMLDocument has several Load methods, see them with their description:

Load(Stream)      Loads the XML document from the specified stream.
Load(String)      Loads the XML document from the specified URL.
Load(TextReader)  Loads the XML document from the specified TextReader.
Load(XmlReader)   Loads the XML document from the specified XmlReader.
LoadXml(string)   Loads the XML document from the specified string.

You're using the last one which is as described used to load XML from a string.

Since you need to load the XML from a file, so you've to use to Load method, as opposed to LoadXml. I think second method is better suited for your situation. You can pass the fullpath of the XML file.

Upvotes: 1

Dan Waterbly
Dan Waterbly

Reputation: 850

This should help you:

XmlDocument doc = new XmlDocument();
doc.Load(file_path);

The method you are calling only loads xml from a string. You need to read it from a file which requires a different method.

Upvotes: 0

BrokenGlass
BrokenGlass

Reputation: 161012

You need

  doc.Load(fileName);

instead of

  doc.LoadXml(xml);

Upvotes: 2

Related Questions