zoukankan      html  css  js  c++  java
  • 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;
    }
    }
  • 相关阅读:
    从应用到平台,云服务架构的演进过程
    从应用到平台,云服务架构的演进过程
    武汉小猫科技-工作总结(1):一图胜万言
    武汉小猫科技-工作总结(1):一图胜万言
    一个App带你学会Retrofit2.0,麻麻再也不用担心我的网络请求了!
    关于创业公司产品开发原则
    关于创业公司产品开发原则
    【Deep learning book】
    【NLP】word2vec
    【python】好书
  • 原文地址:https://www.cnblogs.com/Gabby/p/6246009.html
Copyright © 2011-2022 走看看