• 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;
    }
    }
  • 相关阅读:
    证券公司业务部门深度全解
    转:ORM框架
    深入理解Java:注解(Annotation)基本概念
    Java与.net的区别delegate和event
    XML的四种解析器原理及性能比较
    转: LRU缓存介绍与实现 (Java)
    jquery -- checkbox选中无选中状态
    css -- 背景图片自适应屏幕大小
    javascript -- addEventListener()和removeEventListener
    html5 -- audio标签
  • 原文地址:https://www.cnblogs.com/Gabby/p/6246009.html
Copyright © 2020-2023  润新知