Xml classes

  • Thread starter Thread starter dave
  • Start date Start date
D

dave

Hi,

May someone tell me how can i use the C# XML classes to read an xml file?

I need to make a class with the structre of the XML files and to rean number
of xml files from the same directory and put them data in the class
represent them,
How can i read a number of xml file`s (with the same structre) to my
class???

Thanks,
 
Hi
one way to do that is to read them into a dataset. so if you have an xml
file that look like so
<person>
<name> first last </name>
<age> 30 </age>
<sex> M </sex>
</person>
<person>
<name> fname Lname </name>
<age> 30 </age>
<sex> F </sex>
</person>
---if the file is on root C for example, then you can read it in a dataset
this way
DataSet k = new DataSet();
k.ReadXml("c:\\file.xml");
// the dataset now has a table with the name person that
contains all your data , so to get the age of person in second row
string name =
k.Tables["person"][1]["age"].ToStriing();

i think this is a good an effective way in your case , but there are many
other way
you can read it in an xmldocument object

example:
XmlDocument myDocument =
new XmlDocument();

myDocument.Load("emp.xml");

Console.WriteLine(myDocument.InnerXml.ToString());
Console.ReadLine();
this read the document with its structure , see this example
namespace
CSharp_XMLSample
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
try
{
XmlDocument myDocument = new XmlDocument();
string xmlData;
myDocument.Load("emp.xml");
int i;
int count;
count = 0;
i = 1;
XmlNode node = myDocument.ChildNodes[1];
foreach (XmlNode node1 in node.ChildNodes)
{
Console.WriteLine("\n");

Console.WriteLine(
"The elements under node number: {0}", i);
Console.WriteLine(
"------------------------------------------");
foreach (XmlNode node2 in node1.ChildNodes)
{
Console.WriteLine(
myDocument.DocumentElement.FirstChild.ChildNodes

[count].Name + ": " +
node2.FirstChild.Value);
count = count + 1;
}
i = i + 1;
count = 0;
}
Console.WriteLine("\n");
Console.WriteLine("Press <Enter> to quit...");
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.ReadLine();
}
}
}
}
you can use also the xpath to find data with in document :
XmlDocument XPathDocument = new XmlDocument();
XPathDocument.Load("emp.xml");
XPathNavigator navigator = XPathDocument.CreateNavigator();
XPathExpression XPathExpr = navigator.Compile("sum(//Basic/text())");
Console.WriteLine(navigator.Evaluate(XPathExpr));



in fact there are many ways to do what you want , i think the dataset is
the most fast forward and it also ok with want you want to do
hope that would help
 
Hi dave
one little thing i forgot to mention , you need to use the System.Data
namespace to be able use dataset. other mentioned possiblities are in the
namespace System.Xml , Xpath are in System.Xml.XPath.
 
Back
Top