迭代DataSet提供程序

时间:2009-07-30 11:18:58

标签: c# dataset

我有一个XML文档如下:

<?xml version="1.0" encoding="utf-8" ?>
 <Providers>
    <Provider>
      <ProviderType>Email</ProviderType>
      <ProviderTitle>MyProviderTitle</ProviderTitle>
       <DeliveryRules>
          <PersonalDelivery>true</PersonalDelivery>
       </DeliveryRules>
      <ProviderConfiguration>
    <SendTo>
      <Address>myEmailAddress</Address>
      <Address>myEmailAddress</Address>
    </SendTo>
  </ProviderConfiguration>
</Provider>
    <Provider>
      <ProviderType>Email</ProviderType>
      <ProviderTitle>MyProviderTitle</ProviderTitle>
       <DeliveryRules>
          <PersonalDelivery>true</PersonalDelivery>
       </DeliveryRules>
      <ProviderConfiguration>
    <SendTo>
      <Address>myEmailAddress</Address>
      <Address>myEmailAddress</Address>
    </SendTo>
  </ProviderConfiguration>
</Provider>
</Providers>

现在,当我使用以下内容将其拉入数据集时

 DataSet dsConfiguration = new DataSet();
 dsConfiguration.ReadXml("myfile.xml"));

如何遍历提供商?

2 个答案:

答案 0 :(得分:1)

foreach (var Provider in dsConfiguration.Tables["Provider"].Rows)
{
    // your code here
}

答案 1 :(得分:1)

当谈到更多分层数据时,最好将反序列化为强类型对象图。

这是一个非常快速的实现,应该适用于您的示例文档:

[XmlType("Providers")]
public class Providers : List<Provider> { }

public class Provider
{
    public string ProviderType { get; set; }
    public string ProviderTitle { get; set; }
    public DeliveryRules DeliveryRules { get; set; }
    public ProviderConfiguration ProviderConfiguration { get; set; }
}

public class DeliveryRules
{
    public bool PersonalDelivery { get; set; }
}

public class ProviderConfiguration
{
    [XmlArrayItem("Address")]
    public string[] SendTo { get; set; }
}

public static void Main()
{
    var serializer = new XmlSerializer(typeof (Providers));
    Providers providers;
    using (var stream = File.OpenRead("myfile.xml"))
    {
        providers = (Providers) serializer.Deserialize(stream);
    }
    foreach (var provider in providers)
    {
        Console.WriteLine(provider.ProviderTitle);
        foreach (var address in provider.ProviderConfiguration.SendTo)
        {
            Console.WriteLine("\t" + address);
        }
    }
}

显然,这种方法需要更多的管道工作,但是如果您可以使用描述文档格式的XSD,那么您可以使用XSD.exe工具自动生成所有类。