user1300588
user1300588

Reputation: 63

How to read XML data dynamically in C#/.net?

How can i read XML data dynamically? How can I manage my C# code as generic and dynamic as possible? Based on the requirements I will need to add further folder paths in Xml, which should not affect the written code in a way that it has to be rewritten..

Given a piece of XML as sample:

<?xml version="1.0" standalone="yes"?>
  <HOSTS>
   <Host id = '1'>
     <Extension>txt</Extension>
     <FolderPath>C:/temp</FolderPath>
   </Host>
   <Host id = '2'>
     <Extension>rar</Extension>
     <FolderPath>C:/Sample</FolderPath>
   </Host>
 </HOSTS>

How can I read the host id dynamically? What possibilities do I have?

Upvotes: 0

Views: 6692

Answers (5)

Unril
Unril

Reputation: 106

Best way (for my opinion) for this case is use XML Serialization to strongly typed classes. You can control process with using Attributes.

var serializer = new XmlSerializer(typeof(Hosts));
var hosts = (Hosts)serializer.Deserialize(new StringReader(str));

...

[XmlRoot("HOSTS")]
public class Hosts : List<Host> {}

public class Host {
    [XmlAttribute("id")]
    public int Id { get; set; }

    public string Extension { get; set; }

    public string FolderPath { get; set; }
}

Upvotes: 0

mbx
mbx

Reputation: 6535

Generate an xsd scheme from that sample xml. Modify it as needed and then generate a strongly typed C# class using xsd.exe.

Upvotes: 1

Kapil Khandelwal
Kapil Khandelwal

Reputation: 16144

Use LINQ to XML.

Example: to retrieve host with (id = 1):

string id = "1"


XDocument doc = XDocument.Load("data.xml");
var accounts = from elements in doc.Elements("HOSTS").Elements("Host")
                where elements.Attribute("id").Value = id
                    select elements.FirstOrDefault();

Upvotes: 3

m.edmondson
m.edmondson

Reputation: 30922

Yes - in fact this is a very common task in C#.

There are a couple of ways you could tackle this:

Those links should point you in the right direction.

Upvotes: 6

Cole Tobin
Cole Tobin

Reputation: 9426

Your best bet is to use the System.Xml.XmlDocument class along with System.Xml.XmlDocument.Load(...) for constructors.

Upvotes: 0

Related Questions