Click here to Skip to main content
15,749,184 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Actually i want to read following XML doc and take the serverName to a C# variable.I tried using XML reader .but it didn't work for me. can some one help me on this matter.

XML file is :


XML
<?xml version="1.0"?>
<ServerConfig>
  <ServerName>Testserver</ServerName>
</ServerConfig>


in C# class :


public static string getServer()
        {
            string serverName = "";
            XmlTextReader reader = new XmlTextReader(filename);
            XmlNodeType nType = reader.NodeType;
            //XmlReaderSettings settings = new XmlReaderSettings();
            //settings.IgnoreWhitespace = true;
            //settings.IgnoreComments = true;
            while (reader.Read())
            {
                if (reader.IsStartElement())
                {
                    if (reader.Name == "ServerName")
                    {

                        reader.MoveToFirstAttribute();
                        string attribute = reader.Value.ToString();
                        if (attribute != null)
                        {
                            serverName = attribute.ToString();
                            break;
                        }

                    }
                }
            }
            return (serverName);

        }




so it did nt work!!if some one could tell me how to do it in C#.That would be a great help for me.Thanks in advance!!!
Posted
Updated 2-Apr-12 22:26pm
v2

The following should work:

XML
XElement child;
string str = @"<?xml version=""1.0""?>
    <ServerConfig>
      <ServerName>Testserver</ServerName>
    </ServerConfig>";
XDocument doc = XDocument.Parse(str);
child = doc.Descendants("ServerName").FirstOrDefault();
string name = child.Value;
 
Share this answer
 
You're trying to read node's attribute, but in your example nodes have no attributes. 'Testserver' is value of <servername> node, not attribute.

C#
public static string getServer()
{
    string serverName = "";
    XmlTextReader reader = new XmlTextReader(filename);
    XmlNodeType nType = reader.NodeType;
    //XmlReaderSettings settings = new XmlReaderSettings();
    //settings.IgnoreWhitespace = true;
    //settings.IgnoreComments = true;
    while (reader.Read())
    {
        if (reader.Name == "ServerName")
        {
            serverName = reader.Value;
            break;
        }
    }
    return serverName;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900