0

I am developing an application where I am reading a file, converting the contents into string and then loading the string in XML. But the issue that I am facing is that while loading the string data into XML I am getting an exception of invalid characters. I am using the following piece of code. Could any one help me to resolve the issue. Thank you in advance.

ZipFileEntry objContactXML;

String xmlData = ASCIIEncoding.UTF8.GetString(objContactXML.FileData);

XmlDocument xmlDoc = new XmlDocument();

xmlDoc.LoadXml(xmlData);

Regards, Sanchaita

1 Answer 1

4

Firstly, this is a nasty bit of code:

ASCIIEncoding.UTF8

Please use just Encoding.UTF8 - it's UTF-8, not ASCII.

Now, you can create a StringReader around your XML text data - but you'd actually be better off not turning it into string data at all. It may be encoded in something other than UTF-8 - and the XML parser knows how to deal with that. It's entirely possible that this is why you're running into problems with your current approach. Leave the data in binary and parse that:

using (MemoryStream stream = new MemoryStream(objContactXML.FileData))
{
    document.Load(stream);
}

As an aside, if you're using .NET 3.5 or higher, I would strongly advise you to use LINQ to XML (XDocument etc) instead of the old DOM API. LINQ to XML is a much nicer API.

In LINQ to XML, you'd use:

XDocument document;
using (MemoryStream stream = new MemoryStream(objContactXML.FileData))
{
    document = XDocument.Load(stream);
}
Sign up to request clarification or add additional context in comments.

2 Comments

I am still getting the same exception even after trying the above piece of code.
@Sanchaita: Then that suggests the data isn't valid XML. It's unclear whether it was originally invalid, or whether your ZipFileEntry class is causing a problem - where does that come from?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.