开发者

Loading string into XML Data

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开发者_StackOverflow中文版. 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


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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜