Reputation: 4337
Here i my xml file:-
<?xml version="1.0" encoding="utf-8" ?>
<Ftpservers>
<Ftpserver>
<Name>Client1</Name>
<ServerIP>10.10.10.100:1961</ServerIP>
<UserName>username</UserName>
<Password>pa$#word1</Password>
<EnableSSL>false</EnableSSL>
<UsePassive>false</UsePassive>
</Ftpserver>
<Ftpserver>
<Name>Client2</Name>
<ServerIP>10.10.10.101:1961</ServerIP>
<UserName>username</UserName>
<Password>pa$#word1</Password>
<EnableSSL>false</EnableSSL>
<UsePassive>false</UsePassive>
</Ftpserver>
</Ftpservers>
and here is my c# code:-
public class FtpInfo
{
public string Name { get; set; }
public string ServerIp { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public bool EnableSsl { get; set; }
public bool UsePassive { get; set; }
}
var xmlReader = XDocument.Load("FtpDestination.xml");
var servers = (from f in xmlReader.Descendants("FtpServer")
select new FtpInfo
{
Name = f.Element("Name").Value,
ServerIp = f.Element("ServerIP").Value,
UserName = f.Element("UserName").Value,
Password = f.Element("Password").Value,
EnableSsl = Convert.ToBoolean(f.Element("EnableSSL").Value),
UsePassive = Convert.ToBoolean(f.Element("UsePassive").Value)
}).ToList<FtpInfo>();
foreach(var server in servers)
Console.Write(server.Name);
I am trying to read an xml file using xdocument class. but unable to find why my servers count is always zero. Code does not throw any error but not reading xml data at all. Please advice?
Upvotes: 0
Views: 115
Reputation: 223287
There are two problems with your code,
Ftpserver
not FtpServer
as in your code. (notice the lower case server)Name
for UsePassive
In line:
UsePassive = Convert.ToBoolean(f.Element("Name").Value)
It should be UsePassive
UsePassive = Convert.ToBoolean(f.Element("UsePassive").Value)
Last, although it is not an error, but you don't need .ToList<FtpInfo>();
only ToList
is enough.
So your statement should be:
var servers = (from f in xmlReader.Descendants("Ftpserver")
select new FtpInfo
{
Name = f.Element("Name").Value,
ServerIp = f.Element("ServerIP").Value,
UserName = f.Element("UserName").Value,
Password = f.Element("Password").Value,
EnableSsl = Convert.ToBoolean(f.Element("EnableSSL").Value),
UsePassive = Convert.ToBoolean(f.Element("UsePassive").Value)
}).ToList();
Upvotes: 3
Reputation: 43046
Your Xml nodes are "Ftpserver" but you are querying for "FtpServer". The query therefore returns zero result elements.
Upvotes: 2
Reputation: 31656
UsePassive is failing you in its Boolean conversion, change from Name
to UsePassive
.
Upvotes: 2