简体   繁体   中英

“An error occurred while parsing EntityName” after grabbing content from valid XML

I am reading an XML string with XDocument

XmlReader reader = XmlReader.Create(new StringReader(xmltext));
        reader.Read();
        XDocument xdoc = XDocument.Load(reader);

Then I grab the content of some tags and put them within tags in a different string. When I try to Load this string in the same way I did with the first, I get an error "An error occurred while parsing EntityName. Line 1, position 344.".

I think it should be parsed correctly since it has beem parsed before so I guess I am missing something here.

I am reading and copying the content of the first XML with (string)i.Element("field") .

I am using .net 4

When I grab the content of the xml that I want to use for building another Xml string I use (string)i.Element("field") and this is converting my Xml into string. My next Xml Parsing does not recognize it as an Element anymore so I solved the problem by not using (string) before I read my element, just i.Element("field") and this works.

It sounds like you've got something like this:

<OriginalDocument>
    <Foo>A &amp; B</Foo>
</OriginalDocument>

That A &amp; B A &amp; B represents the text A & B . So when you grab the text from the element, you'll get the string "A & B". If you then use that to build a new element like this:

string foo = "<Foo>" + fooText + "</Foo>";

then you'll end up with invalid XML like this:

<Foo>A & B</Foo>

Basically, you shouldn't be constructing XML in text form. It's not clear what you're really trying to achieve, but you can copy an element from one place to another pretty easily in XElement form; you shouldn't need to build a string and then reparse it.

So after spending hours on this issue: it turns out that if you have an ampersand symbol ("&") or any other XML escape characters within your xml string, it will always fail will you try read the XML. TO solve this, replace the special characters with their escaped string format

 YourXmlString = YourXmlString.Replace("'", "&apos;").Replace("\"", "&quot;").Replace(">", "&gt;").Replace("<", "&lt;").Replace("&", "&amp;");

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