XML的学习运用
[csharp]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Xml;
using System.Windows.Forms;
namespace XmlApplication
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
xmlConfig();
LoadXML();
}
/// <summary>
/// 生成XML
/// </summary>
private void xmlConfig()
{
XmlDocument doc = new XmlDocument();
XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "gb2312", null);
doc.AppendChild(dec);
XmlElement root = doc.CreateElement("唐诗");
doc.AppendChild(root);
XmlNode node = doc.CreateElement("五言绝句");
root.AppendChild(node);
XmlNode node1 = doc.CreateElement("作者");
System.Xml.XmlAttribute ab = doc.CreateAttribute("字号");
ab.Value = "太白";
node1.InnerText = "李白";
node1.Attributes.Append(ab);
node.AppendChild(node1);
XmlNode node2 = doc.CreateElement("标题");
node2.InnerText = "静夜思";
node.AppendChild(node2);
XmlNode node3 = doc.CreateElement("内容");
node3.InnerText = "床前明月光,疑是地上霜。举头望明月,低头思故乡。";
node.AppendChild(node3);
doc.Save(Application.StartupPath+@"\tangshi.xml");
}
/// <summary>
/// 获取指定节点的属性和值
/// </summary>
private void LoadXML()
{
XmlDocument doc = new XmlDocument();
doc.Load(Application.StartupPath + @"\tangshi.xml");
XmlElement element = doc.DocumentElement;
XmlNodeList list = doc.GetElementsByTagName("作者");
for (int i = 0; i < list.Count; i++)
{
textBox2.Text = list[i].InnerText;
if (list[i].Attributes[i].Name == "字号")
{
textBox5.Text = list[i].Attributes[i].Value;
}
}
XmlNode node = doc.SelectSingleNode("唐诗/五言绝句/作者");
textBox2.Text = node.InnerText;
for (int j = 0; j < node.Attributes.Count; j++)
{
if (node.Attributes[j].Name == "字号")
{
textBox5.Text = list[j].Attributes[j].Value;
}
}
//using (XmlReader reader = XmlReader.Create(Application.StartupPath + @"\tangshi.xml"))
//{
// while (reader.Read())
// {
// switch (reader.NodeType)
// {
// case XmlNodeType.Element:
// string value=reader.Value;
// break;
// case XmlNodeType.Text:
// break;
// default: break;
// }
// }
//}
using (XmlTextReader reader = new XmlTextReader(Application.StartupPath + @"\tangshi.xml"))
{
&nb
补充:Web开发 , 其他 ,