Nikki
Nikki

Reputation: 13

XML reading from web and displaying content

I'm reading a file like from the web:

<?xml version='1.0' encoding='UTF-8'?>
<eveapi version="2">
  <currentTime>2011-07-30 16:08:53</currentTime>
  <result>
    <rowset name="characters" key="characterID" columns="name,characterID,corporationName,corporationID">
      <row name="Conqrad Echerie" characterID="91048359" corporationName="Federal Navy Academy" corporationID="1000168" />
    </rowset>
  </result>
  <cachedUntil>2011-07-30 17:05:48</cachedUntil>
</eveapi>

im still new to XML and i see there are many ways to read XML data, is there a certain way im going to want to do this? what i want to do is load all the data into a StreamReader? and then use get; set; to pull the data later?

Upvotes: 1

Views: 132

Answers (3)

Interarticle
Interarticle

Reputation: 385

If you need to use the data in the easy way, especially when you're new to XML, use XmlDocument. To load the document:

using System.Xml;
using System.IO;
public class someclass {
    void somemethod () {
        //Initiate the XmlDocument object
        XmlDocument xdoc;
        //To load from file
        xdoc.Load("SomeFolder\\SomeFile.xml");
        //Or to load from XmlTextReader, from a file for example
        FileStream fs = FileStream("SomeFolder\\SomeFile.xml", FileMode.Open, FileAccess.Read);
        XmlTextReader reader = new XmlTextReader(fs);
        xdoc.Load(reader);
        //In fact, you can load the stream directly
        xdoc.Load(fs);

        //Or, you can load from a string
        xdoc.LoadXml(@"<rootElement>
                    <element1>value1</element1>
                    <element2>value2</element2>
                    </rootElement>");
    }
}

I personally find XmlDocument far easier to use for navigating an Xml file.

To use it efficiently, you need to learn XPath. For example, to get the name of the first row:

string name = xdoc.SelectSingleNode("/eveapi/result/rowset/row").Attribute["name"].InnerText;

or even more XPath:

string name = xdoc.SelectSingleNode("/eveapi/result/rowset/row/@name").InnerText;

you can even filter:

XmlNodeList elems = xdoc.SelectNodes("//*[@name=\"characters\"]") 

gives you the rowset element.

But that's off topic.

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062502

If you want object-based access, put the example xml in a file and run

xsd.exe my.xml
xsd.exe my.xsd /classes

this will create my.cs which is an object model similar to the xml that you can use with XmlSerializer:

var ser = new XmlSerializer(typeof(eveapi));
var obj = (eveapi)ser.Deserialize(source);

Upvotes: 1

Related Questions