简体   繁体   中英

XmlDocument class fails to load a file that contains a node with C# code

I have an xml file with a node that contains some c# code.

<Script Name="WrapText">
        var sb = new System.Text.StringBuilder();
        int lastSpaceIndex = 0;

            for(int i = 0; i < paragraph.length; i++)
            {
                var curChar = paragraph[i];
                sb.Append(curChar);

                if (System.Char.IsWhiteSpace(curChar))
                {
                    lastSpaceIndex = i;
                }

                if (i % splitlength == 0)
                {
                    if (lastSpaceIndex != 0)
                    {
                        sb[lastSpaceIndex] = '\n';
                    }
                }
            }

        return sb.ToString();
</Script>

when i try to load this using an XmlDocument and XmlReader classes in C# like this:

XmlReader xReader = XmlReader.Create(new MemoryStream(ASCIIEncoding.UTF8.GetBytes(imml)),  _ReaderSettings);
    XmlDocument xDoc = new XmlDocument();
    xDoc.Load(xReader);

I get this error:

Name cannot begin with the ' ' character, hexadecimal value 0x20. Line 25, position 21.

If I remove the for loop line, it loads the file without any problems.

Why is this happening?

Creation of XML by hand/with string concatenation always causes such problems: you < is not properly encoded and as result < paragraph.length; i++)... < paragraph.length; i++)... is treated as element name.

You should encode all special characters as required. (ie &lt; for < ). See http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references for compact list.

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