数据集中的主详细信息数据绑定即使存在也找不到子表

问题描述 投票:0回答:1
c# xml .net-core dataset relationship
1个回答
0
投票

尝试 xml linq

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

namespace ConsoleApp10
{
    class Program
    {
        static string FILENAME = @"c:\temp\test.xml";
         static void Main(string[] args)
        {

            XDocument doc = XDocument.Load(FILENAME);

            int maxParameters = doc.Root.Elements("command").Select(x => x.Elements("parameter").Count()).Max();

            //create data table
            DataTable restDs = new DataTable();
            restDs.Columns.Add("Name", typeof(string));
            restDs.Columns.Add("Method", typeof(string));
            restDs.Columns.Add("Path", typeof(string));
            for(int i = 0; i < maxParameters; i++)
            {
                restDs.Columns.Add("Param " + i, typeof(string));
            }

            foreach(XElement command in doc.Descendants("command"))
            {
                DataRow row = restDs.Rows.Add();
                row["Name"] = (string)command.Attribute("name");
                row["Method"] = (string)command.Attribute("method");
                row["Path"] = (string)command.Attribute("path");
                int count = 0;
                foreach (XElement parameter in command.Elements("parameter"))
                {
                    row["Param " + count] = (string)parameter.Attribute("name");
                    count++;
                }
            }


        }
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.