C#如何在窗体加载的时候读取XML文件内容
展开全部
using System.Collections.Generic;
using System.Text;
using System.Xml;
namespace XmlExample
{
class Program
{
static void Main(string[] args)
{
string xmlFilePath = @"X:\about.net\example\XmlExample\1.xml";
XmlDocument doc = new XmlDocument();
doc.Load(xmlFilePath);
//使用xpath表达式选择文档中所有的student子节点
XmlNodeList studentNodeList = doc.SelectNodes("/students/student");
if (studentNodeList != null)
{
foreach (XmlNode studentNode in studentNodeList)
{
//通过Attributes获得属性名字为name的属性
string name = studentNode.Attributes["name"].Value;
Console.WriteLine("Student:" + name);
//通过SelectSingleNode方法获得当前节点下的courses子节点
XmlNode coursesNode = studentNode.SelectSingleNode("courses");
//通过ChildNodes属性获得courseNode的所有一级子节点
XmlNodeList courseNodeList = coursesNode.ChildNodes;
if (courseNodeList != null)
{
foreach (XmlNode courseNode in courseNodeList)
{
Console.Write("\t");
Console.Write(courseNode.Attributes["name"].Value);
Console.Write("老师评语");
//通过FirstNode属性可以获得课程节点的第一个子节点,LastNode可以获得最后一个子节点
XmlNode teacherCommentNode = courseNode.FirstChild;
//读取CData节点
XmlCDataSection cdata = (XmlCDataSection)teacherCommentNode.FirstChild;
Console.WriteLine(cdata.InnerText.Trim());
}
}
}
}
Console.Write("\r\nPress any key to continue....");
Console.Read();
}
}
}
using System.Text;
using System.Xml;
namespace XmlExample
{
class Program
{
static void Main(string[] args)
{
string xmlFilePath = @"X:\about.net\example\XmlExample\1.xml";
XmlDocument doc = new XmlDocument();
doc.Load(xmlFilePath);
//使用xpath表达式选择文档中所有的student子节点
XmlNodeList studentNodeList = doc.SelectNodes("/students/student");
if (studentNodeList != null)
{
foreach (XmlNode studentNode in studentNodeList)
{
//通过Attributes获得属性名字为name的属性
string name = studentNode.Attributes["name"].Value;
Console.WriteLine("Student:" + name);
//通过SelectSingleNode方法获得当前节点下的courses子节点
XmlNode coursesNode = studentNode.SelectSingleNode("courses");
//通过ChildNodes属性获得courseNode的所有一级子节点
XmlNodeList courseNodeList = coursesNode.ChildNodes;
if (courseNodeList != null)
{
foreach (XmlNode courseNode in courseNodeList)
{
Console.Write("\t");
Console.Write(courseNode.Attributes["name"].Value);
Console.Write("老师评语");
//通过FirstNode属性可以获得课程节点的第一个子节点,LastNode可以获得最后一个子节点
XmlNode teacherCommentNode = courseNode.FirstChild;
//读取CData节点
XmlCDataSection cdata = (XmlCDataSection)teacherCommentNode.FirstChild;
Console.WriteLine(cdata.InnerText.Trim());
}
}
}
}
Console.Write("\r\nPress any key to continue....");
Console.Read();
}
}
}
追问
我做的是窗体程序 不是控制台 应该从哪里下手...从public Form里写还是自己新写一个一个函数?求指教 谢谢
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询