C#中读取XML错误解决: System.Xml.XmlException: “Element”是无效的 XmlNodeType。

  在用C#写Xml解析时,抛出一个错误: System.Xml.XmlException: “Element”是无效的 XmlNodeType。在网上找了很久,没有结果,决定自己来找原因。

我在读取下面这样的xml格式的文件时,我想读取Text里面的文本,然后我就使用xml解析:

<Abstract>
<Text>Hello Emma!!<p>error</p></Text>
</Abstract>

代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Text;
using System.Xml;
using System.IO;
using System.IO.Compression;
using System.Collections;
using System.Text.RegularExpressions;

  static void Main(string[] args) {
  XmlTextReader reader = new XmlTextReader(filePath);
 while (reader.Read())
                    {
      
                        switch (reader.Name)
                        {
  case "Abstract":
 XmlReader subtreeReader1 = reader.ReadSubtree();
                                while (subtreeReader1.ReadToFollowing("Text")) {
                                    abstractContent += subtreeReader1.ReadContentAsString();
                                    hasAbstract = true; 
                                }
                               
                                subtreeReader1.Close();
                                break;
}
}

然后就报错误: System.Xml.XmlException: “Element”是无效的 XmlNodeType。

我去查看了,错误是由于<Text>里面还包含<p>这样的elment,所以没有办法转成string。把代码改为下面的就可以了。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Text;
using System.Xml;
using System.IO;
using System.IO.Compression;
using System.Collections;
using System.Text.RegularExpressions;

  static void Main(string[] args) {
  XmlTextReader reader = new XmlTextReader(filePath);
 while (reader.Read())
                    {
      
                        switch (reader.Name)
                        {
  case "Abstract":
 XmlReader subtreeReader1 = reader.ReadSubtree();
                                while (subtreeReader1.ReadToFollowing("Text")) {
                                    abstractContent += subtreeReader1.ReadString();
                                    hasAbstract = true; 
                                }
                               
                                subtreeReader1.Close();
                                break;
}
}
原文地址:https://www.cnblogs.com/Gabby/p/6246009.html