0

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?

0

5 Answers 5

6

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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();

Comments

1

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

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.