Accessing embedded xml file using C#

I have recently been embedding xml files into assemblies so the information can be accessed in code.

This is how I get a reference to the current assembly where the code and xml file is residing

Assembly currentAssembly = Assembly.GetExecutingAssembly();

I invoke the method to get my xml file by doing the following:

Stream stream = currentAssembly.GetManifestResourceStream(this.GetType(), “ValidationRules.xml”);

I create a new XmlDocument and load the content of the xml file into there:

XmlDocument doc = new XmlDocument();
doc.Load(stream);

Given my xml is kind of like this:

<?xml version=”1.0″ encoding=”utf-8″ ?>

<Fields>

<Field>
<Name>Question 1a</Name>
<ValidationRule>Mandatory</ValidationRule>
<ValidationMessage>The Question 1a field cannot be empty</ValidationMessage>
<DependentFields>Question 2a</DependentFields>
</Field>
<Field>
<Name>Question1b</Name>
<ValidationRule>Mandatory</ValidationRule>
<ValidationMessage>Question 1b cannot be empty</ValidationMessage>
<DependentFields>Question2b</DependentFields>
</Field>

</Fields>

Depending on the structure of your xml, I would iterate through the element nodes using a foreach. I would go through each element by doing the following:

¬†foreach (XmlElement xmlField in doc.SelectNodes(“/Fields/Field”))
{
string fieldName = xmlField.SelectSingleNode(“Name”).InnerText;
string dependentFields = xmlField.SelectSingleNode(“DependentFields”).InnerText;
}

I can now use the data from the xml file to do other processing in my code.

Advertisements