0

I am wondering if it's possible to have a generic class that extracts the table data from an XML file? Like a loop or something via C#?

Here's the sample XML:

<Report>
 <Template>
  <Stylesheet>
   <Table>
    <tbody>
     <tr>
      <td>
       <p align="left">Test A</p>
      </td>
      <td>
       <p align="center">Test B</p>
      </td>
     </tr>
     <tr>
      <td>
       <p align="left">Test C</p>
      </td>
      <td>
       <p align="center">Test D</p>
      </td>
     </tr>
    </tbody>
   </Table>
  </Stylesheet>
 </Template>
</Report>

I need to get those data, Test A Test B Test C and Test D

Any help? Thank you.

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
Qwerty
  • 489
  • 1
  • 4
  • 13

2 Answers2

0

If you need all td childnodes content,try:

XDocument xml = XDocument.Load(xmlPath);
var list = from e in xml.Descendants("td").Elements() select e.Value;

only need p:

XDocument xml = XDocument.Load(xmlPath);
var list = from e in xml.Descendants("td").Elements("p") select e.Value;
melody zhou
  • 148
  • 4
0

Here is a complete solution

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication120
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("align", typeof(string));
            dt.Columns.Add("value", typeof(string));

            XDocument doc = XDocument.Load(FILENAME);

            foreach (XElement p in doc.Descendants("p"))
            {
                dt.Rows.Add(new object[] {
                    (string)p.Attribute("align"),
                    (string)p
                });
            }

        }

    }

}
jdweng
  • 33,250
  • 2
  • 15
  • 20