HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Parsing an XML File for a single word/phrase

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
filexmlsingleparsingforwordphrase

Problem

this is a small part of my code that allows me to request a file through a load balancer, reading this XML file gives me the server's name (only node inside the XML Document) if the machine isn't inside the LAN then it won't be able to query the website. I give it a longer timeout to make sure that I don't get a ton of errors emailed to me if the network is laggy.

Here is the XML file Structure.



JSODYAPP01T



Here is the Code that retrieves the information

WebRequest request = WebRequest.Create(xmlLocation);
request.Timeout = 90000;

using (WebResponse response = request.GetResponse())
using (XmlReader xmlReader = XmlReader.Create(response.GetResponseStream()))
{
    while (xmlReader.Read())
    {
        if (xmlReader.NodeType == XmlNodeType.Text)
        {
            serverName = xmlReader.Value.ToString();
            serverName = serverName.Replace("\r", "");
            serverName = serverName.Replace("\n", "");
            serverName = serverName.Replace(" ", "");
        }
    }
}


is there a better way of doing this?

Solution

Linq to XML is your friend

var serverName = XDocument.Load(response.GetResponseStream()).Element("Server").Value;


Your code will be easily broken if someone adds a node to the XML, and your code should be as flexible as possible. Never do such an assumption (It's gonna be the first node)

Your method is blocking, consider making it asynchronous.

using (var response = await request.GetResponseAsync()){

}


And by the way, C# got type inference, so why bother typing the type? Use var instead

var request = WebRequest.Create(xmlLocation);

Code Snippets

var serverName = XDocument.Load(response.GetResponseStream()).Element("Server").Value;
using (var response = await request.GetResponseAsync()){

}
var request = WebRequest.Create(xmlLocation);

Context

StackExchange Code Review Q#68227, answer score: 10

Revisions (0)

No revisions yet.