<?xml version="1.0" encoding="utf-8" ?> <Books> <!--A:Books的第一个孩子节点就是此注释A,注释A的兄弟节点book西游记--> <book title="西游记"> <!--B:author的孩子节点是吴承恩,兄弟节点是price--> <author>吴承恩</author> <!--B:吴承恩是文本节点,没有孩子和兄弟--> <price>150</price> </book> <!--A:以下均同与上面的注释--> <book title="红楼梦"> <author>曹雪芹</author> <price>160</price> </book> <book title="三国演义"> <author>罗贯中</author> <price>120</price> </book> <book title="水浒传"> <author>施耐恩</author> <price>100</price> </book> </Books> using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Xml; namespace XmlListBox { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnLoad_Click(object sender, EventArgs e) { lbXml.Items.Clear(); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load("../../Books.xml"); XmlNode xmlRootElement= xmlDoc.DocumentElement; ShowXml(xmlRootElement); } private void ShowXml(XmlNode xmlRootElement) { recurseXmlDocument(xmlRootElement,0); } /// <summary> /// 递归遍历books.xml /// </summary> /// <param name="curNode">从根元素开始递归遍历</param> /// <param name="indent">显示缩进的大小</param> private void recurseXmlDocument(XmlNode curNode,int indent) { if (curNode == null) { return; } //如果XmlElement是元素节点 if (curNode is XmlElement) { //获取节点的限定名(标签名) string content = curNode.Name; //如果当前元素节点有属性,则显示属性值 if (curNode.Attributes.Count != 0) { //默认其只有一个属性 content += ":" + curNode.Attributes[0].Value.ToString(); } content = content.PadLeft(content.Length + indent); lbXml.Items.Add(content); //首先遍历该元素节点curNode的孩子节点 if (curNode.HasChildNodes) { recurseXmlDocument(curNode.FirstChild,indent+2); } //其次遍历该元素节点curNode的兄弟节点 if (curNode.NextSibling != null) { recurseXmlDocument(curNode.NextSibling, indent); } } else if (curNode is XmlText) //当前节点是文本节点 { string content = curNode.Value.ToString(); content = content.PadLeft(content.Length + indent); lbXml.Items.Add(content); } else if (curNode is XmlComment) //当前节点是注释节点 { string content = "<!--" + curNode.Value.ToString() + "-->"; content = content.PadLeft(content.Length + indent); lbXml.Items.Add(content); //注释节点有兄弟节点 if (curNode.NextSibling != null) recurseXmlDocument(curNode.NextSibling,indent); } } } }