简体   繁体   中英

Remove “&” from input stream when generating XML

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 &amp; 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);

you can use "& amp;" to escape "&".

In xml document, there are some characters should be escaped.

& ---- &amp;

< ---- &lt;

> ---- &gt;

" ---- &quot;

' ---- &apos;

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM