Reading XML file
C# Code Example
This C# program continuously reads an XML file from a device located at http://192.168.0.60/status.xml
and prints the values of specific XML nodes ( this means the measured values ).
using System;
using System.Threading.Tasks;
using System.Xml;
namespace xml_file_read
{
internal class Program
{
private static string DeviceUrl = "http://192.168.0.60/status.xml"; //your IP address here
static async Task Main(string[] args)
{
while (true)
{
try
{
XmlTextReader reader = new XmlTextReader(Program.DeviceUrl);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(reader);
XmlNodeList nodesV1 = xmlDoc.GetElementsByTagName("v1");
XmlNodeList nodesV2 = xmlDoc.GetElementsByTagName("v2");
XmlNodeList nodesV3 = xmlDoc.GetElementsByTagName("v3");
if (nodesV1.Count > 0)
{
Console.WriteLine($"v1: {nodesV1.Item(0).InnerText} V");
}
if (nodesV2.Count > 0)
{
Console.WriteLine($"v2: {nodesV2.Item(0).InnerText} V");
}
if (nodesV3.Count > 0)
{
Console.WriteLine($"v3: {nodesV3.Item(0).InnerText} V");
}
Console.WriteLine($"------------");
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
// Wait for 5 seconds before the next iteration
await Task.Delay(1000);
}
}
}
}
Commentary
Here is a detailed comment on the functionality of the code :
- Namespace Imports: The program imports several namespaces:
System
: Provides basic system functionality.System.Threading.Tasks
: Provides classes for asynchronous programming.System.Xml
: Provides classes for XML processing.
- URL Declaration:
The program declares a static string
DeviceUrl
which holds the URL of the XML file to be read. - Infinite Loop:
The program enters an infinite loop to continually read data from the XML file.
- XML Reading and Parsing:
Within the loop, the program performs the following steps:
XmlTextReader reader = new XmlTextReader(Program.DeviceUrl);
: Creates anXmlTextReader
to read from the URL.XmlDocument xmlDoc = new XmlDocument();
: Creates anXmlDocument
object.xmlDoc.Load(reader);
: Loads the XML document from the reader.XmlNodeList nodesV1 = xmlDoc.GetElementsByTagName("v1");
: Retrieves nodes named "v1".XmlNodeList nodesV2 = xmlDoc.GetElementsByTagName("v2");
: Retrieves nodes named "v2".XmlNodeList nodesV3 = xmlDoc.GetElementsByTagName("v3");
: Retrieves nodes named "v3".- Conditional statements to print the inner text of the nodes if they exist.
reader.Close();
: Closes the reader after processing.
- Exception Handling:
The program includes a
try-catch
block to handle any exceptions that may occur during the XML reading and parsing process. If an exception occurs, it prints an error message. - Delay Between Iterations:
The program uses
await Task.Delay(1000);
to wait for 1 second before the next iteration of the loop.