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
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);
use HttpEncoder.HtmlEncode()
http://msdn.microsoft.com/en-us/library/system.web.util.httpencoder.aspx
you can use "& amp;" to escape "&".
In xml document, there are some characters should be escaped.
& ---- &
< ---- <
> ---- >
" ---- "
' ---- '
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.