views:

46

answers:

2
<?xml version="1.0" encoding="utf-8" ?>
<root>
  <MyData>
    <MyField>SomeValueHere1</MyField>
    <MyComplexData>
      <MyComplexDataField1 property="1"></MyComplexDataField1>
      <MyComplexDataField2 someproperty"value1"> value1 </MyComplexDataField1>
    </MyComplexData>
  </MyData>
  <MyData>
    <MyField>SomeValueHere11</MyField>
    <MyComplexData>
      <MyComplexDataField1 property="4"></MyComplexDataField1>
      <MyComplexDataField2 someproperty="value1"> value2 </MyComplexDataField1>
      </MyComplexData>
  </MyData>
  <MyData>
    <MyField>SomeValueHere13</MyField>
    <MyComplexData>
      <MyComplexDataField1 property="5"></MyComplexDataField1>
      <MyComplexDataField2 someproperty="value1"> value </MyComplexDataField1>
    </MyComplexData>
  </MyData>
  .
  .
  .
  .
</root>

I would like to get the collection of MyData objects ( assuming that MyData object can be serialized and deserialized into the mentioned XMLNode)

What are all the System.Xml API(s) I should look into? - .Net and C#

Please guide me.

A: 

This is the .NET 2.0 way of doing things - using a XmlDocument from System.Xml.

XmlDocument xdoc = new XmlDocument();

xdoc.Load('(your file name)');

XmlNodeList myDataList = xdoc.SelectNodes('//MyData');

foreach(XmlNode dataNode in myDataList)
{
  // do whatever oyu need to do with your myData nodes
}

Check out the MSDN documentation on the XmlDocument class. This should give you an idea of how to deal with XML documents.

The XML Document approach is great for small to mid-size document (less than a few MByte in size) since it loads the entire document into memory at once, and allows you to navigate around in the document and manipulate it.

With .NET 3.5 and up, you get the new "LINQ to XML" approach using XDocument - check out the MSDN documentation on it here.

Marc

marc_s
A: 

If you want to use XML serialisation, you could declare something like that :

public class root
{

    [XmlElement("MyData")]
    public List<MyData> Items { get, set }

}

public class MyData
{
    ...
}

To perform the deserialization and loop through the MyData objects, use the following code :

XmlSerializer xs = new XmlSerializer(typeof(root));
root r;
using (StreamReader reader = new StreamReader(filename))
{
    r = xs.Deserialize(reader) as root;
}

foreach(MyData d in r.Items)
{
    ...
}
Thomas Levesque