Search code examples
c#xmlxmlreader

C# xmlReader simple XML


I've got simple XML like:

<?xml version="1.0" encoding="utf-8"?>
<ftp>
    <address>ftp://ftp.example.com/</address>
    <user>jondoe</user>
    <password>Password123</password>
</ftp>

And I wanted to use this C# code:

using (XmlReader reader = XmlReader.Create(xmlPath))
{
    reader.ReadToFollowing("address");
    string ftpAddress = reader.ReadElementContentAsString();
    reader.ReadToFollowing("user");
    string ftpUser = reader.ReadElementContentAsString();
    reader.ReadToFollowing("password");
    string ftpPw = reader.ReadElementContentAsString();
}

It's working fine when I want to read only one content, like address but it fails when I want to read more/next ones. I thought this would be logical but it seems like it's not. How to read that XML and all elements of it: address, user and password? I would like to use XmlReader for that.


Solution

  • The simplest form I can think of would be this one:

    XElement xml = XElement.Parse(File.ReadAllText(xmlPath));
    var ftpAddress = xml.Element("address").Value;
    var ftpUser = xml.Element("user").Value;
    var ftpPwd = xml.Element("user").Value;
    

    Of course you should add some safety by checking for null values and if the file exists..

    Update:

    I would implement a failsafe version this way:

    if (!File.Exists(xmlPath))
        throw new FileNotFoundException(string.Format("The FTP configuration file {0} is missing", xmlPath));
    
    XElement xml = XElement.Parse(File.ReadAllText(xmlPath));
    var ftpAddress = GetConfigValue(xml, "address");
    var ftpUser = GetConfigValue(xml, "user");
    var ftpPwd = GetConfigValue(xml, "password");
    

    With GetConfigValue like this:

    private static string GetConfigValue(XContainer parent, XName name)
    {
        var element = parent.Element(name);
    
        if (element == null)
            throw new ArgumentException(string.Format("Invalid configuration file, missing element {0}", name));
    
        return element.Value;
    }