Reputation: 35213
HttpContext.Current.Response.ContentType = "text/xml";
HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;
HttpPostedFile file = HttpContext.Current.Request.Files[0];
// If file.InputSteam contains an "&", exception is thrown
XDocument doc = XDocument.Load(XmlReader.Create(file.InputStream));
HttpContext.Current.Response.Write(doc);
Is there any way to replace &
with &
before generating the xml document? My current code crashes whenever the file contains a &
.
Thanks
Upvotes: 0
Views: 384
Reputation: 101
you can use "& amp;" to escape "&".
In xml document, there are some characters should be escaped.
& ---- &
< ---- <
> ---- >
" ---- "
' ---- '
Upvotes: 0
Reputation: 1503090
Your code will only crash if it's not valid XML. For example, this should be fine:
<foo>A & B</foo>
If you've actually got
<foo>A & B</foo>
Then you haven't got an XML file. You may have something which looks a bit like XML, but it isn't really valid XML.
The best approach here isn't to transform the data on the fly - it's to fix the source of the data so that it's real XML. There's really no excuse for anything producing invalid XML in this day and age.
Additionally, there's no reason to use XmlReader.Create
here - just use
XDocument doc = XDocument.Load(file.InputStream);
Upvotes: 2
Reputation: 13450
use HttpEncoder.HtmlEncode()
http://msdn.microsoft.com/en-us/library/system.web.util.httpencoder.aspx
Upvotes: 0