Johan
Johan

Reputation: 35213

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

Upvotes: 0

Views: 384

Answers (3)

keep fool
keep fool

Reputation: 101

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

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

& ---- &

< ---- &lt;

> ---- &gt;

" ---- &quot;

' ---- &apos;

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503090

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

Upvotes: 2

Related Questions