0

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.

2
  • 2
    Have you considered creating a basic view model, then deserialize the xml to your view model? Commented Oct 16, 2014 at 13:26
  • I just want a simple method to read that XML. Nothing extensive like building view model for XML. Commented Oct 16, 2014 at 13:27

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

thank you. It's working pretty well. And could you please tell me how you would do those safety checks the simple/elegant way?
Thank you Denis Thomas, that is all I need!

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.