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;
}
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM