Search code examples
c#xmlasp.net-mvc

Illegal characters in path error when reading xml file


I am trying to read the contents of a XML file. The code is throwing an error on the line that is loading the XML file.

Here is an example of the XML file

<?xml version="1.0" encoding="ISO-8859-1"?> 
<user userID="1356748"> 
    <name first="Joe" last="Sample" /> 
    <version>MACHVR</version> 
    <aptitude name="Mental Acuity" id="A1">4</aptitude> 
    <aptitude name="Business Terms" id="A2">3</aptitude> 
    <aptitude name="Memory Recall" id="A3">9</aptitude> 
    <aptitude name="Vocabulary" id="A4">4</aptitude> 
    <aptitude name="Numerical Perception" id="A5">3</aptitude> 
    <aptitude name="Mechanical Interest" id="A6">4</aptitude> 
    <aptitude name="Math" id="A7">7</aptitude> 
</user>

Here is the code I am using to read it:

public Assessment GetXMLData(string UserId, string Secondary, string FirstName, string LastName, string AcctPassword)
{
    string URL = "http://www.myurl.com";
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
    request.Method = "POST";

    string postdata = "UserId=" + UserID + "&FirstName=" + FirstName +
        "&LastName=" + LastName + "&SecondaryAccount=" + Secondary +
        "&Password=" + AcctPassword;

    byte[] byteArray = Encoding.UTF8.GetBytes(postdata);
    request.ContentType = "application/x-www-form-urlencoded";
    request.ContentLength = byteArray.Length;

    Assessment test = new Assessment();
    Stream dataStream = request.GetRequestStream();
    dataStream.Write(byteArray, 0, byteArray.Length);
    dataStream.Close();

    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

    using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
    {
        string ResponseFromServer = streamReader.ReadToEnd();

        XDocument doc = XDocument.Load(ResponseFromServer);
        var query = from c in doc.Descendants("aptitude")
                    select c;
                    
        //some more code            
    }
}

The error is being thrown on the line

XDocument doc = XDocument.Load(ResponseFromServer)

I tried adding the @ sign so then it was:

XDocument doc = XDocument.Load(@ResponseFromServer);

Then I tried using this to escape the quotes in the string and kept the @ sign

ResponseFromServer = ResponseFromServer.Replace("\"", "\"\"")
XDocument doc = XDocument.Load(@ResponseFromServer); 

But I am still getting that error.


Solution

  • The overload of XDocument.Load that takes a string value expects the string to be a file name.

    From the code example, it looks like you already have a StreamReader with the actual XML content. Have you tried to pass that as an argument instead?

    var doc = XDocument.Load(streamReader);
    

    If you truly need to read an XML string, use XDocument.Parse instead of Load.