毛毛的小窝 — 关注技术交流、让我们一起成长

导航

C# 读取XML

访问的XML两种模型:

在程序中访问进而操作XML文件一般有两种模型,分别是使用DOM(文档对象模型)和流模型,使用DOM的好处在于它允许编辑和更新XML文档,可以随机访问文档中的数据,可以使用XPath查询,但是,DOM的缺点在于它需要一次性的加载整个文档到内存中,对于大型的文档,这会造成资源问题。流模型很好的解决了这个问题,因为它对XML文件的访问采用的是流的概念,也就是说,任何时候在内存中只有当前节点,但它也有它的不足,它是只读的,仅向前的,不能在文档中执行向后导航操作。

流模型中的变体: 

流模型每次迭代XML文档中的一个节点,适合于处理较大的文档,所耗内存空间小。流模型中有两种变体——“推”模型和“拉”模型。 

推模型也就是常说的SAX,SAX是一种靠事件驱动的模型,也就是说:它每发现一个节点就用推模型引发一个事件,而我们必须编写这些事件的处理程序,这样的做法非常的不灵活,也很麻烦。 

.NET中使用的是基于“拉”模型的实现方案,“拉”模型在遍历文档时会把感兴趣的文档部分从读取器中拉出,不需要引发事件,允许我们以编程的方式访问文档,这大大的提高了灵活性,在性能上“拉”模型可以选择性的处理节点,而SAX每发现一个节点都会通知客户机,从而,使用“拉”模型可以提高Application的整体效率。在.NET中“拉”模型是作为XmlReader类实现的,下面看一下该类的继承结构: 

我们今天来讲一下该体系结构中的XmlTextReader类,该类提供对Xml文件进行读取的功能,它可以验证文档是否格式良好,如果不是格式良好的Xml文档,该类在读取过程中将会抛出XmlException异常,可使用该类提供的一些方法对文档节点进行读取,筛选等操作以及得到节点的名称和值,请牢记:XmlTextReader是基于流模型的实现,打个不恰当的比喻,XML文件就好象水源,闸一开水就流出,流过了就流过了不会也不可以往回流。内存中任何时候只有当前节点,你可以使用XmlTextReader类的Read()方法读取下一个节点。
namespace XMLReading 



using System; 

using System.Xml; 

using System.Windows.Forms; 

using System.ComponentModel; 



/// <summary> 

/// Xml文件读取器 

/// </summary> 


public class XmlReader : IDisposable 


    
private string _xmlPath; 

    
private const string _errMsg = "Error Occurred While Reading "

    
private ListBox _listBox; 

    
private XmlTextReader xmlTxtRd; 



XmlReader 的构造器 



XmlReader 的资源释放方法 



XmlReader 的属性 



/// <summary> 

/// 遍历Xml文件 

/// </summary> 


public void EachXml() 



    
this._listBox.Items.Clear(); 

    
this.xmlTxtRd = new XmlTextReader(this._xmlPath); 



    
try 

    


        
while(xmlTxtRd.Read()) 

        


            
this._listBox.Items.Add(this.xmlTxtRd.Value); 

        }
 

    }


    
catch(XmlException exp) 

    


        
throw new XmlException(_errMsg + this._xmlPath + exp.ToString()); 

    }
 

    
finally 

    


        
if (this.xmlTxtRd != null

            
this.xmlTxtRd.Close(); 

    }
 

}
 



/// <summary> 

/// 读取Xml文件的节点类型 

/// </summary> 


public void ReadXmlByNodeType() 



this._listBox.Items.Clear(); 

this.xmlTxtRd = new XmlTextReader(this._xmlPath); 



try 



while(xmlTxtRd.Read()) 



this._listBox.Items.Add(this.xmlTxtRd.NodeType.ToString()); 

}
 

}
 

catch(XmlException exp) 



throw new XmlException(_errMsg + this._xmlPath + exp.ToString()); 

}
 

finally 



if (this.xmlTxtRd != null

this.xmlTxtRd.Close(); 

}
 

}
 



/// <summary> 

/// 根据节点类型过滤Xml文档 

/// </summary> 

/// <param name="xmlNType">XmlNodeType 节点类型的数组</param> 


public void FilterByNodeType(XmlNodeType[] xmlNType) 



this._listBox.Items.Clear(); 

this.xmlTxtRd = new XmlTextReader(this._xmlPath); 



try 



while(xmlTxtRd.Read()) 



for (int i = 0; i < xmlNType.Length; i++



if (xmlTxtRd.NodeType == xmlNType[i]) 



this._listBox.Items.Add(xmlTxtRd.Name + " is Type " + xmlTxtRd.NodeType.ToString()); 

}
 

}
 

}
 

}
 

catch(XmlException exp) 



throw new XmlException(_errMsg + this.xmlPath + exp.ToString()); 

}
 

finally 



if (this.xmlTxtRd != null

this.xmlTxtRd.Close(); 

}
 

}
 



/// <summary> 

/// 读取Xml文件的所有文本节点值 

/// </summary> 


public void ReadXmlTextValue() 



this._listBox.Items.Clear(); 

this.xmlTxtRd = new XmlTextReader(this._xmlPath); 



try 



while(xmlTxtRd.Read()) 



if (xmlTxtRd.NodeType == XmlNodeType.Text) 



this._listBox.Items.Add(xmlTxtRd.Value); 

}
 

}
 

}
 

catch(XmlException xmlExp) 



throw new XmlException(_errMsg + this._xmlPath + xmlExp.ToString()); 

}
 

finally 



if (this.xmlTxtRd != null

this.xmlTxtRd.Close(); 

}
 

}
 



/// <summary> 

/// 读取Xml文件的属性 

/// </summary> 


public void ReadXmlAttributes() 



this._listBox.Items.Clear(); 

this.xmlTxtRd = new XmlTextReader(this._xmlPath); 



try 



while(xmlTxtRd.Read()) 



if (xmlTxtRd.NodeType == XmlNodeType.Element) 



if (xmlTxtRd.HasAttributes) 



this._listBox.Items.Add("The Element " + xmlTxtRd.Name + " has " + xmlTxtRd.AttributeCount + " Attributes"); 

this._listBox.Items.Add("The Attributes are:"); 



while(xmlTxtRd.MoveToNextAttribute()) 



this._listBox.Items.Add(xmlTxtRd.Name + " = " + xmlTxtRd.Value); 

}
 

}
 

else 



this._listBox.Items.Add("The Element " + xmlTxtRd.Name + " has no Attribute"); 

}
 

this._listBox.Items.Add(""); 

}
 

}
 

}
 

catch(XmlException xmlExp) 



throw new XmlException(_errMsg + this._xmlPath + xmlExp.ToString()); 

}
 

finally 



if (this.xmlTxtRd != null

this.xmlTxtRd.Close(); 

}
 

}
 



/// <summary> 

/// 读取Xml文件的命名空间 

/// </summary> 


public void ReadXmlNamespace() 



this._listBox.Items.Clear(); 

this.xmlTxtRd = new XmlTextReader(this._xmlPath); 



try 



while(xmlTxtRd.Read()) 



if (xmlTxtRd.NodeType == XmlNodeType.Element && xmlTxtRd.Prefix != ""



this._listBox.Items.Add("The Prefix " + xmlTxtRd.Prefix + " is associated with namespace " + xmlTxtRd.NamespaceURI); 

this._listBox.Items.Add("The Element with the local name " + xmlTxtRd.LocalName + " is associated with" + " the namespace " + xmlTxtRd.NamespaceURI); 

}
 

if (xmlTxtRd.NodeType == XmlNodeType.Element && xmlTxtRd.HasAttributes) 



while(xmlTxtRd.MoveToNextAttribute()) 



if (xmlTxtRd.Prefix != ""



this._listBox.Items.Add("The Prefix " + xmlTxtRd.Prefix + " is associated with namespace " + xmlTxtRd.NamespaceURI); 

this._listBox.Items.Add("The Attribute with the local name " + xmlTxtRd.LocalName + " is associated with the namespace " + xmlTxtRd.NamespaceURI); 

}
 

}
 

}
 

}
 

}
 

catch(XmlException xmlExp) 



throw new XmlException(_errMsg + this._xmlPath + xmlExp.ToString()); 

}
 

finally 



if (this.xmlTxtRd != null

this.xmlTxtRd.Close(); 

}
 

}
 



/// <summary> 

/// 读取整个Xml文件 

/// </summary> 


public void ReadXml() 



string attAndEle = string.Empty; 

this._listBox.Items.Clear(); 

this.xmlTxtRd = new XmlTextReader(this._xmlPath); 



try 



while(xmlTxtRd.Read()) 



if (xmlTxtRd.NodeType == XmlNodeType.XmlDeclaration) 

this._listBox.Items.Add(string.Format("<?{0} {1} ?>",xmlTxtRd.Name,xmlTxtRd.Value)); 

else if (xmlTxtRd.NodeType == XmlNodeType.Element) 



attAndEle 
= string.Format("<{0} ",xmlTxtRd.Name); 

if (xmlTxtRd.HasAttributes) 



while(xmlTxtRd.MoveToNextAttribute()) 



attAndEle 
= attAndEle + string.Format("{0}='{1}' ",xmlTxtRd.Name,xmlTxtRd.Value); 

}
 

}
 

attAndEle 
= attAndEle.Trim() + ">"

this._listBox.Items.Add(attAndEle); 

}
 

else if (xmlTxtRd.NodeType == XmlNodeType.EndElement) 

this._listBox.Items.Add(string.Format("</{0}>",xmlTxtRd.Name)); 

else if (xmlTxtRd.NodeType == XmlNodeType.Text) 

this._listBox.Items.Add(xmlTxtRd.Value); 

}
 

}
 

catch(XmlException xmlExp) 



throw new XmlException(_errMsg + this._xmlPath + xmlExp.ToString()); 

}
 

finally 



if (this.xmlTxtRd != null

this.xmlTxtRd.Close(); 

}
 

}
 

}
 

}
 



namespace XMLReading 



using System; 

using System.Drawing; 

using System.Collections; 

using System.ComponentModel; 

using System.Windows.Forms; 

using System.Data; 

using System.Xml; 



public class Form1 : System.Windows.Forms.Form 



private System.Windows.Forms.ListBox listBox1; 

private System.Windows.Forms.Button button1; 

private System.Windows.Forms.Button button2; 

private System.Windows.Forms.Button button3; 

private System.Windows.Forms.Button button4; 

private System.Windows.Forms.Button button5; 

private System.Windows.Forms.Button button6; 

private System.Windows.Forms.Button button7; 

private string xmlPath; 

private XmlReader xRead; 

/// <summary> 

/// 必需的设计器变量。 

/// </summary> 


private System.ComponentModel.Container components = null



public Form1() 



InitializeComponent(); 

}
 



/// <summary> 

/// 清理所有正在使用的资源。 

/// </summary> 


protected override void Dispose( bool disposing ) 



if( disposing ) 



if (components != null



components.Dispose(); 

}
 

}
 

base.Dispose( disposing ); 

}
 



Windows 窗体设计器生成的代码 



/// <summary> 

/// 应用程序的主入口点。 

/// </summary> 


[STAThread] 

static void Main() 



    Application.Run(
new Form1()); 

}
 


/// <summary>
/// Example1按纽遍历文档读取数据
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>

private void button1_Click(object sender, System.EventArgs e) 



    xRead 
= new XmlReader(this.xmlPath,this.listBox1); 

    
try 
    

        xRead.EachXml(); 
    }
 
    
catch(XmlException xmlExp) 
    

        MessageBox.Show(xmlExp.ToString(),
"Error",MessageBoxButtons.OK,MessageBoxIcon.Error); 
    }
 
    
catch(Exception exp) 
    

        MessageBox.Show(exp.ToString(),
"Error",MessageBoxButtons.OK,MessageBoxIcon.Error); 
    }
 
    
finally 
    

        xRead.Dispose(); 
    }
 
}
 


/// <summary>
/// 读取Xml文件的节点类型 
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>

private void button2_Click(object sender, System.EventArgs e) 



xRead 
= new XmlReader(this.xmlPath,this.listBox1); 



try 



xRead.ReadXmlByNodeType(); 

}
 

catch(XmlException xmlExp) 



MessageBox.Show(xmlExp.ToString(),
"Error",MessageBoxButtons.OK,MessageBoxIcon.Error); 

}
 

catch(Exception exp) 



MessageBox.Show(exp.ToString(),
"Error",MessageBoxButtons.OK,MessageBoxIcon.Error); 

}
 

finally 



xRead.Dispose(); 

}
 

}
 



private void button3_Click(object sender, System.EventArgs e) 



XmlNodeType[] xmlNType 
= {XmlNodeType.Element, XmlNodeType.EndElement, XmlNodeType.XmlDeclaration}

xRead 
= new XmlReader(this.xmlPath, this.listBox1); 



try 



xRead.FilterByNodeType(xmlNType); 

}
 

catch(XmlException xmlExp) 



MessageBox.Show(xmlExp.ToString(),
"Error",MessageBoxButtons.OK,MessageBoxIcon.Error); 

}
 

catch(Exception exp) 



MessageBox.Show(exp.ToString(),
"Error",MessageBoxButtons.OK,MessageBoxIcon.Error); 

}
 

finally 



xRead.Dispose(); 

}
 

}
 



private void button4_Click(object sender, System.EventArgs e) 



xRead 
= new XmlReader(this.xmlPath, this.listBox1); 



try 



xRead.ReadXmlTextValue(); 

}
 

catch(XmlException xmlExp) 



MessageBox.Show(xmlExp.ToString(),
"Error",MessageBoxButtons.OK,MessageBoxIcon.Error); 

}
 

catch(Exception exp) 



MessageBox.Show(exp.ToString(),
"Error",MessageBoxButtons.OK,MessageBoxIcon.Error); 

}
 

finally 



xRead.Dispose(); 

}
 

}
 



private void button5_Click(object sender, System.EventArgs e) 



xRead 
= new XmlReader(this.xmlPath, this.listBox1); 



try 



xRead.ReadXmlAttributes(); 

}
 

catch(XmlException xmlExp) 



MessageBox.Show(xmlExp.ToString(),
"Error",MessageBoxButtons.OK,MessageBoxIcon.Error); 

}
 

catch(Exception exp) 



MessageBox.Show(exp.ToString(),
"Error",MessageBoxButtons.OK,MessageBoxIcon.Error); 

}
 

finally 



xRead.Dispose(); 

}
 

}
 



private void button6_Click(object sender, System.EventArgs e) 



xRead 
= new XmlReader(this.xmlPath, this.listBox1); 



try 



xRead.ReadXmlNamespace(); 

}
 

catch(XmlException xmlExp) 



MessageBox.Show(xmlExp.ToString(),
"Error",MessageBoxButtons.OK,MessageBoxIcon.Error); 

}
 

catch(Exception exp) 



MessageBox.Show(exp.ToString(),
"Error",MessageBoxButtons.OK,MessageBoxIcon.Error); 

}
 

finally 



xRead.Dispose(); 

}
 

}
 



private void button7_Click(object sender, System.EventArgs e) 



xRead 
= new XmlReader(this.xmlPath, this.listBox1); 



try 



xRead.ReadXml(); 

}
 

catch(XmlException xmlExp) 



MessageBox.Show(xmlExp.ToString(),
"Error",MessageBoxButtons.OK,MessageBoxIcon.Error); 

}
 

catch(Exception exp) 



MessageBox.Show(exp.ToString(),
"Error",MessageBoxButtons.OK,MessageBoxIcon.Error); 

}
 

finally 



xRead.Dispose(); 

}
 

}
 

}
 

}
 
程序中使用到的XML文件如下:

sample.xml
<?xml version="1.0" encoding="utf-8" ?>

<Invoices date="28/11/2001" xmlns:cat="uri:Business-Categories">

  
<customers custname="Chile Wines Inc" phone="1241 923 56332" email="cw@yahoo.com.cn" custid="192398" delivery="international" offerID="27">

    
<cat:businfo>Wine Division South</cat:businfo>

    
<cat:businfo>Beer Division North</cat:businfo>

    
<order orderID="OID921" batchid="123">

      
<details>

        
<items cat:num="2">

          
<item>Rancagua While</item>

          
<item>Rancagua Red</item>

        
</items>

      
</details>

    
</order>

    
<order orderID="OID927">

      
<details>

        
<items num="5">

          
<item>Chillan Red</item>

          
<item>Rancagua While</item>

          
<item>Santiago Red</item>

          
<item>Rancagua While</item>

          
<item>Rancagua Red</item>

        
</items>

      
</details>

    
</order>

    
<order orderID="OID931" batchid="123">

      
<details>

        
<items num="6">

          
<item>Rancegao Red</item>

          
<item>Sutothad Black</item>

          
<item>BlackNme Blue</item>

          
<item>Booklist Red</item>

          
<item>Rancegao White</item>

        
</items>

      
</details>

    
</order>

  
</customers>

</Invoices>

posted on 2007-05-31 16:08  mjgforever  阅读(840)  评论(1编辑  收藏  举报