简体   繁体   中英

Name cannot begin with the ' ' character, hexadecimal value 0x20

I have gone through a lot of answers for this but was not able to solve issue so asking.

I am getting my xml in a string. It consist of "< 6" as content in some node values.

As a result I am getting an exception

Name cannot begin with the ' ' character, hexadecimal value 0x20. Line 3270, position 54.

Here is the code:

string patternToReplaceAnd = "&(?![a-z#]+;)";
Regex reg = new Regex(patternToReplaceAnd);
xml = reg.Replace(xml, "&amp;");
XDocument xDoc = XDocument.Parse(xml);

Can anyone help me out?

You say you're getting your XML in a string. You're not. You're getting garbage in a string.

If the garbage is really important to you then you can try and convert it to XML. How you do that depends on just how bad it is, which we can't really judge.

Much better: refuse to accept shoddy goods. Go back to the supplier and tell them to generate real XML.

I do realize that this question is old but I came across the same problem today and I hope my answer will help someone who may land on this question in the future.

The problem is the content that includes < followed by the space . You will have to replace that content with &lt; so that It is not recognised as a malformed xml start tag .

xml = xml.Replace('< ',"&lt; "); //make sure you include the space after < to avoid replacing actual tags.
XDocument xDoc = XDocument.Parse(xml);

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