【问题标题】:XmlException when loading an XML file with certain characters加载具有某些字符的 XML 文件时出现 XmlException
【发布时间】:2013-11-09 17:12:02
【问题描述】:

我需要使用XmlDocument 类来加载一个 XML 文件:

var doc = new XmlDocument();
doc.Load(filename);

不幸的是,当我的 XML 中有特定的字符用于表示我的数据时,我得到了一个 XmlException,特别是我有一个如下所示的节点:

<rect data="string with invalid characters: † ¶"/>

所以,禁止使用的字符是:

我如何才能毫无例外地加载文件并将这些字符留在我的 XML 文件中?

【问题讨论】:

    标签: c# xml exception character-encoding xmldocument


    【解决方案1】:

    您需要将这些字符替换为数字字符引用。类似于您如何将 > 和

    edit:我必须在 & 之后添加一个空格,以避免编辑器实际拾取和解释字符。只需删除正在使用的空间 - 你明白了。

    【讨论】:

      【解决方案2】:

      或者,如果您无法控制 XML 的源并且只需要将所有值读入数据库或其他内容,则可以使用 XmlTextReader 逐行读取 xml,在元素上停止您知道可能包含错误数据,并读取该元素的字符。我过去不得不这样做。像这样的

      static void Main(string[] args)
          {
              var xtr = new XmlTextReader("");
              xtr.Normalization = false;
      
              while (xtr.Read())
              {
                  if(xtr.IsStartElement("Row")) // My xml doc contains many row elements
                  {
                      var fields = new string[6];
                      while(xtr.Read())
                      {
                          for (int i = 0; i < 6; i++) // I know my xml only has six child elements per row
                          {
                              while(!xtr.IsStartElement())
                              {
                                  xtr.Read(); // We're not interested in hitting the end elements
                              }
      
                              if(i == 1) // I know my special characters are in the second child element of my row
                              {
                                  var charBuff = new char[255];
                                  xtr.ReadChars(charBuff, 0, 255); // I know there will be a maximum of 255 characters
      
                                  fields[i] = new string(charBuff);
                              }
                              else
                              {
                                  fields[i] = xtr.ReadElementContentAsString();
                              }
                          }
                      }
                  }
              }
          }
      

      【讨论】:

        猜你喜欢
        • 2023-03-31
        • 1970-01-01
        • 1970-01-01
        • 2011-05-17
        • 2016-04-15
        • 1970-01-01
        • 2020-07-20
        • 2019-04-26
        • 1970-01-01
        相关资源
        最近更新 更多