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;
    }
    }
  • 相关阅读:
    scrollview嵌套recyclerview显示不全现象
    scrollview嵌套recyclerview卡顿现象
    设计模式——原型模式
    设计模式——访问者模式
    设计模式——外观模式
    设计模式——责任链模式
    设计模式——组合模式
    设计模式——享元模式
    设计模式——迭代器模式
    设计模式——备忘录模式
  • 原文地址:https://www.cnblogs.com/Gabby/p/6246009.html
Copyright © 2011-2022 走看看