JL.
JL.

Reputation: 81262

Iterate over DataSet providers

I have an XML document as below:

<?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>

Now when I pull this into a dataset using:

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

How can I iterate through providers?

Upvotes: 1

Views: 699

Answers (2)

Nathan Baulch
Nathan Baulch

Reputation: 20683

When it comes to more hierarchical data, you're much better off deserializing to a strongly typed object graph.

Here is a very quick implementation that should work for your example document:

[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);
        }
    }
}

Obviously this approach requires more plumbing work but if you can get your hands on an XSD that describes your document's format then you can automatically generate all your classes using the XSD.exe tool.

Upvotes: 1

HuBeZa
HuBeZa

Reputation: 4761

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

Upvotes: 1

Related Questions