将xml转换为数据表

时间:2016-02-19 20:37:13

标签: c# xml datatables

我在这个模板中有一个XML文件

<tests>
   <x>
      <a></a>
      <b></b>
      <c></c>
   </x>
   <y>
      <a></a>
      <b></b>
      <c></c>
   </y>
   <z>
      <a></a>
      <b></b>
      <c></c>
  </z>
</tests>

我想只将<x>...</x>内的所有内容转换为DataTable。

我该怎么做?

2 个答案:

答案 0 :(得分:0)

这是一种方式:

public DataTable CreateDataTable(string fileName)
{
    XElement xml = XElement.Load(fileName);

    var tempRows = from x in xml.Descendants("x")                       
                   select new
                   {
                       A = (string)x.Element("a"),
                       B = (string)x.Element("b"),
                       C = (string)x.Element("c")
                   };

    DataTable dt = new DataTable();
    dt.Columns.Add("a", typeof(string));
    dt.Columns.Add("b", typeof(string));
    dt.Columns.Add("c", typeof(string));            

    foreach (var tempRow in tempRows)
    {
        dt.Rows.Add(tempRow.A, tempRow.B, tempRow.C);
    }

    return dt;
}

答案 1 :(得分:0)

纯粹的javascript就是将XML从服务器上获取并解析它:

var xmlData = "<tests><x><a>1</a><b>1</b><c>1</c></x><y><a>2</a><b>2</b><c>2</c></y><z><a>3</a><b>3</b><c>3</c></z></tests>";
$(function(){
    var example = $("#example").DataTable({
        columns:[{
            title: "Row A"
        },{
            title: "Row B"
        },{
            title: "Row C"
        }]
    });
    $.ajax({
        type: "POST",
        dataType: "xml",
        url: "/echo/xml/",
        data : { 
            "xml": xmlData,
            "delay": 1
        },
        success: function(xml) {
            $(xml).find("tests").children().each(function(k, v){
                var abc = [];
                abc.push($(v).children("a").text())
                abc.push($(v).children("b").text())
                abc.push($(v).children("c").text())
                example.row.add(abc);
            })
            example.draw();
        }  
    });    
});

工作示例here但请注意:我已经冒昧地使用数据填充XML。

相关问题