An error occurred while parsing EntityName. Line1, position 844

前端 未结 5 1465
星月不相逢
星月不相逢 2020-12-25 10:22

I have got the following exception from the below code block.

An error occurred while parsing EntityName. Line1, position 844.

I was trying

相关标签:
5条回答
  • 2020-12-25 10:39

    Just replace them:

    Not valid in XML elements:

    "   "
    '   '
    <   &lt;
    >   &gt;
    &   &amp;
    

      public static string UnescapeXMLValue(string xmlString)
      {
        if (xmlString == null)
            throw new ArgumentNullException("xmlString")
    
        return xmlString.Replace("&apos;", "'").Replace("&quot;", "\"").Replace("&gt;", ">").Replace("&lt;", "<").Replace("&amp;", "&");
      }
    
     public static string EscapeXMLValue(string xmlString)
      {
    
        if (xmlString == null)
            throw new ArgumentNullException("xmlString")
    
        return xmlString.Replace("'","&apos;").Replace( "\"", "&quot;").Replace(">","&gt;").Replace( "<","&lt;").Replace( "&","&amp;");
      }
    
    0 讨论(0)
  • 2020-12-25 10:39

    You can use: SecurityElement.Escape(XML string)

    Reference link: https://msdn.microsoft.com/en-us/library/system.security.securityelement.escape(v=vs.110).aspx

    0 讨论(0)
  • 2020-12-25 10:56

    If your XML is being constructed with string concatenation then you'll be wanting to escape it. & should become &amp; while < and > should become &lt; and &gt; respectively.

    There may be others too. Of course you should really use a proper XML encoder rather than trying to do it yourself for many reasons.

    0 讨论(0)
  • 2020-12-25 11:00

    As the data comes from some data base, the problem can be hot-fixed in the context you described, but I would strongly recommend a different approach. The ampersand symbol should not have occured in the xml in the first place, as discussed here. Please clarify how the xml is generated and address the problem there.

    0 讨论(0)
  • 2020-12-25 11:01

    This has already been answered, but found a nicer way of achieving the same outcome by doing this in .NET 4.5 by using the Escape method as below:

    var xmlWithEscapedCharacters = SecurityElement.Escape(xmlWithoutEscapedCharacters);
    

    and then just plug that string into the XML that is being generated.

    Link: MSDN - SecurityElement.Escape Method

    0 讨论(0)
提交回复
热议问题