XML files are a powerful tool to contain any structured data required for a .NET application or ASP .NET website to run. These files are based on the main principles of HTML and when you create an XML file, you should follow these few rules:

  • The XML file must start with a declaration instructing how the file should be read as. For example: <?xml version=”1.0″ encoding=”UTF-8″?>
  • The file must contain one root element opened right after the XML declaration and closed at the file’s end. Once the root tag is closed, you cannot add anything after it because this would make the file invalid. Example:
<?xml version="1.0" encoding="UTF-8"?>
<!--locations is the root tag-->
<locations>
    <location>
    ...
    </location>
    <location>
    ...
    </location>
    ...
</locations>
  • Be careful with small and capital letters, as XML is case sensitive;
  • Each element can contain attributes. For example: <location id=”1″ name=”Earth”>;
  • If you write the XML file manually, all special characters not related to the XML synthax must be encoded through HTML Entity Name encoding. Using the proper C# classes to read or write into XML files will ensure all special characters are decoded and encoded properly. For example:
&amp; returns &
&gt; returns >
and so on

Writing and Reading from XML Files

XML file operations are usually performed by the XDocument class and its methods. Here’s an example code writing into XML files:

XDocument doc = new XDocument(
   new XDeclaration("1.0", null, "yes"),
   new XComment("Created with the XDocument class."),

   new XElement("locations",
   new XElement("location",
   new XAttribute("id", 1),
   new XAttribute("name", "Earth"),
   new XElement("hashumans", "no")),

   new XElement("location",
   new XAttribute("id", 2),
   new XAttribute("name", "Mars"),
   new XElement("hashumans", "no"))
 
   )
);
// Save the document.
doc.Save(file);

This code will generate the following XML structure:

<?xml version="1.0" standalone="yes" ?>
<locations>
    <location id="1" name="Earth">
        <hashumans>yes</hashumans>
    </location>
    <location id="2" name="Mars">
        <hashumans>no</hashumans>
    </location>
</locations>

Reading from that XML will look like that:

// Load the document.
XDocument doc = XDocument.Load(file);

// Looping through each location
foreach (XElement element in doc.Element("locations").Elements("location"))
{
   string id = element.Attribute("id"); // Returns the location id
   string name = element.Attribute("name"); // Returns the location name
   bool hasHumans = (bool)element.Element("hashumans"); // Returns the value of the inner element
} 

Was this article helpful?