Search code examples
c#xmlutf-16

Error parsing XML


I am trying to parse the string contents of an XML file that contains special characters in to an XDocument for further processing when I keep getting the following error:

Name cannot begin with the '.' character, hexadecimal value 0x00. Line 1, position 8.

I do not have control over this file. All I can do is parse it from a network share that I have read access to. The file contents are as follows:

<?xml version="1.0" encoding="utf-16"?>
<ns0:SAEErr xmlns:ns0="http://xyz">
<ErrorInformation>olsfdhfaskldhfksajdfkajsf</ErrorInformation>
<OriginalMessage>慐浹湥䥴Ɽ慐浹湥却慴畴䍳摯ⱥ慐</OriginalMessage>
</ns0:SAEErr>

The code to parse the file above is as follows:

StringBuilder sb = new StringBuilder();
        sb.Append("<root>");
        sb.Append(FileUtil.ReadFileContent(fileName));
        sb.Append("</root>");

        return XDocument.Parse(sb.ToString());        

What am I missing here?

Thanks in advance!

UPDATE: The following code update did it:

 XElement body = XElement.Load(fileName);

 return new XDocument(new XDeclaration("1.0", "utf-16", "no"), body);

Thanks Henk!


Solution

  • When reading the file with XElement.Load() I can only reproduce your error after change utf-16 to utf-8 in the processing line. So it is indeed an Encoding error.

    Edit:

    Your code:

      StringBuilder sb = new StringBuilder();
      sb.Append("<root>");
      sb.Append(FileUtil.ReadFileContent(fileName));  // Encoding ??
      sb.Append("</root>");
      return XDocument.Parse(sb.ToString()); 
    

    Try:

      XElement body = XElement.Load(fileName); 
      XDocument doc = new XDocument(new XElement( "root", body));