0

I am receiving an XML file over a socket and want to retrieve all the values inside the XML by converting it into a c# class object

Please guide me how to do this

I need all the values of SNo,File,It and MaxIt

P.S. I am using Visual Studio 2010

Here is my XML file:

<?xml version="1.0" standalone="yes"?>
<NewDataSet>
  <default.xml>
    <SNo>31</SNo>
    <File>300K</File>
    <It>5</It>
    <MaxIt>10</MaxIt>
  </default.xml>
  <default.xml>
    <SNo>32</SNo>
    <File>200K</File>
    <It>5</It>
    <MaxIt>10</MaxIt>
  </default.xml>
</NewDataSet>

[EDITED] Please note that I need to use these values dynamically as I am working on a utility which sends XML file to another system via sockets. I dont think I can ude xsd here

Karan Goel
  • 25
  • 4
  • possible duplicate of [Generate C# class from XML](http://stackoverflow.com/questions/4203540/generate-c-sharp-class-from-xml) – Sani Huttunen Nov 27 '14 at 10:17
  • An introduction to either XML parsing (ie. manually extract the values with which to create a class instance) or XML Serialisation (.NET does it all for you: but can be hard to get things just right) is far too long for a [SO] answer. – Richard Nov 27 '14 at 10:18
  • I was just writing an aswer on how you could automatically generate a class with xsd.exe but as the question is closed I can't post it, sorry. – Jontatas Nov 27 '14 at 10:26
  • One of many options: xsd.exe + XmlSerializer. Now your can start learning. – Renatas M. Nov 27 '14 at 10:28
  • Sorry but I dont think I can use xsd here as I want to use that values dynamically. Looks like I have to do XML Parsing here. – Karan Goel Nov 27 '14 at 10:47

1 Answers1

-1

To get all nodes use XPath expression /default/default. The first slash means that the node must be a root node. SelectNodes method returns collection XmlNodeList which will contain the nodes. To get value of sub node you can simply index XmlNode with the node name: xmlNode["SNo"].InnerText. See the example below.

XmlDocument xml = new XmlDocument();
xml.LoadXml(myXmlString); // suppose that myXmlString contains "<default>...</default>"

XmlNodeList xnList = xml.SelectNodes("/default/default");
foreach (XmlNode xn in xnList)
{
  string ss= xn["SNo"].InnerText;
  string vv= xn["File"].InnerText;
  Console.WriteLine("Name: {0} {1}", ss, vv);
}
MMM
  • 3,132
  • 3
  • 20
  • 32