0
<?xml version="1.0" encoding="utf-8" ?>
<class name="EmployeeData.Employee">
  <property emp="1">
    <empid>12345678</empid>
    <empname>ABC1</empname>
    <project>XYZ1</project>
  </property>
  <property emp="2">
    <empid>87654321</empid>
    <empname>ABC2</empname>
    <project>XYZ2</project>
  </property>
</class>

In the above XML doc I have two nodes by name property. I need to parse through it and store the values: "12345678","ABC1","XYZ1" in one object and "87654321","ABC2","XYZ2" in another. Also I should be able to use the two objects later whenever and wherever I need. How can I do this?

mac mohan
  • 165
  • 1
  • 9
A_K
  • 5
  • 3

2 Answers2

1

Use LINQ2XML

var doc=XDocument.Load(url);
var output= doc.Elements("property").Select(x=>
              new
              {
                    empid=x.Element("empid").Value,
                    empname=x.Element("empname").Value,
                    project=x.Element("project").Value
              }
);

Now you can iterate over output

foreach(var property in output)
{
    property.empid;
    property.empname;
    property.project;
}
Anirudha
  • 32,393
  • 7
  • 68
  • 89
0

First get each <property>

XmlDocument xdoctest = new XmlDocument();    
xdoctest.LoadXml("...");   
XmlNodeList nodes = xdoctest.SelectNodes("class/property");

Then loop through each property node, loop through each element of that node and get value. In this example I append to a StringBuilder but edit it to suit your needs.

foreach (XmlNode node in nodes)
{
    StringBuilder nodeString = new StringBuilder();
    foreach(XmlElement elm in node)
    {
        nodeString.Append(elm.InnerText + ",");
    }
    // Remove last ,
    nodeString = new StringBuilder(nodeString.ToString().Substring(0, nodeString.Length - 1));
    Console.WriteLine(nodeString);
}

Based on the XML you gave the output is:

12345678,ABC1,XYZ1
87654321,ABC2,XYZ2
andrewb
  • 2,995
  • 7
  • 54
  • 95