我的xml操作练习题

刚学xml操作那会写的一些小例子,现在忘的差不多了,回顾一下…

(一)xmlReader 读取xml, 只进只读,速度快…

xmlReader
public partial class Form1 : Form
{
private XmlReaderSettings set;

public Form1()
{
InitializeComponent();
set = new XmlReaderSettings();
set.IgnoreComments = true;
set.IgnoreWhitespace = true;
set.ConformanceLevel = ConformanceLevel.Document;
set.CloseInput = true;//关闭基流
}

private void button3_Click(object sender, EventArgs e)
{
StringBuilder sb
= new StringBuilder();
XmlReader reader
= XmlReader.Create("XML.xml",set);
reader.Read();
sb.Append(
"<?" + reader.Name + " " + reader.Value + "?>");
reader.Read();
sb.Append(reader.ReadOuterXml());
reader.Close();
this.textBox1.Text = sb.ToString();
}

private void button2_Click(object sender, EventArgs e)
{
XmlReader fullReader
= XmlReader.Create("XML.xml",set);
fullReader.ReadToDescendant(
"student");
fullReader.ReadToNextSibling(
"student"); //注:读取到与当前标记相同的下一个 "同级元素"

XmlReader reader
= fullReader.ReadSubtree(); // subtree
reader.Read();

this.textBox1.Text = reader.ReadOuterXml();

}

private void button1_Click(object sender, EventArgs e)
{
StringBuilder sb
= new StringBuilder();

XmlReader reader
= XmlReader.Create("XML.xml", set);
reader.Read();

while(reader.Read())
{
if(reader.IsEmptyElement)
{
sb.Append(
"<" + reader.Name +this.GetAttribtue(reader) + "/> \r\n");
continue;
}
else if (reader.NodeType == XmlNodeType.Element)
{
sb.Append(
"<" + reader.Name);
if (reader.AttributeCount > 0)
{
sb.Append(
this.GetAttribtue(reader));
}
sb.Append(
"> \r\n");
}
else if (reader.NodeType == XmlNodeType.EndElement)
{
sb.Append(
"</" + reader.Name + "> \r\n");
}
else if (reader.NodeType == XmlNodeType.Text)
{
sb.Append(reader.Value
+ "\r\n");
}
}

reader.Close();
this.textBox1.Text = sb.ToString();
}


private string GetAttribtue(XmlReader xr)
{
string str = "";
for (int i = 0; i < xr.AttributeCount; i++)
{
xr.MoveToAttribute(i);
str
+= " " + xr.Name + "=\"" + xr.Value + "\"";
}
return str;
}
}

附:测试用的xml文件

<?xml version="1.0" encoding="utf-8" ?>
<grade>
<student>
<name>张三</name>
<age>20</age>
<tel num="0311-7260311"></tel>
</student>
<student>
<name>李四</name>
<age>30</age>
<tel num ="0311-7260312"></tel>
</student>
<student>
<name>王五</name>
<age>25</age>
<tel num ="0311-7260313"></tel>
</student>
</grade>



(二)由于xmlReader是只进只读的, 所以想要对xml进行修改操作就要考虑换方法了。 该demo使用XmlDocument 实现对xml的增删改查。
注意了:该demo中使用了一个自定义控件,不过它不影响xml的相关的操作。

public partial class Form1 : Form
{
private XmlDocument xmldoc;

public Form1()
{
InitializeComponent();
xmldoc
= new XmlDocument();
xmldoc.Load(
"Config.xml");
}

private void btnAdd_Click(object sender, EventArgs e)
{
if (this.txtName.Text.Trim() == "")
{
MessageBox.Show(
"请输入姓名","信息提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
return;
}
if (this.txtAge.Text.Trim() == "")
{
MessageBox.Show(
"请输入年龄","信息提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
return;
}
if (this.txtPhone.Text.Trim() == "")
{
MessageBox.Show(
"请输入电话号码","信息提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
return;
}
if (this.Exist(this.txtName.Text.Trim()))
{
MessageBox.Show(
"该学生已经存在不允许重复添加","信息提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
return;
}


XmlNode root
= xmldoc.SelectSingleNode("root");
XmlElement student
= xmldoc.CreateElement("student");
XmlElement name
= xmldoc.CreateElement("name");
name.InnerText
= this.txtName.Text.Trim();
XmlElement age
= xmldoc.CreateElement("age");
age.InnerText
= this.txtAge.Text.Trim();
XmlElement phone
= xmldoc.CreateElement("phone");
XmlAttribute phoneAttri
= xmldoc.CreateAttribute("num");
phoneAttri.InnerText
= this.txtPhone.Text.Trim();
phone.Attributes.Append(phoneAttri);
root.AppendChild(student);

student.AppendChild(name);
student.AppendChild(age);
student.AppendChild(phone);

xmldoc.Save(
"Config.xml");

this.RefreshControl();
}

private void RefreshControl()
{
this.flowLayoutPanel.Controls.Clear();
XmlNode root
= xmldoc.SelectSingleNode("root");
XmlNodeList list
= root.SelectNodes("student");
foreach (XmlNode node in list)
{
XMLControl control
= new XMLControl();
control.Stuname
= node["name"].InnerText;
control.Age
= int.Parse(node["age"].InnerText);
control.Phone
= node["phone"].Attributes["num"].InnerText;
control.ModiEvent
+= new EventHandler(control_ModiEvent);
control.RemoveEvent
+= new EventHandler(control_RemoveEvent);
this.flowLayoutPanel.Controls.Add(control);
}
}

void control_RemoveEvent(object sender, EventArgs e)
{
DialogResult dr
= MessageBox.Show("是否删除该学生","信息提示",MessageBoxButtons.YesNo,MessageBoxIcon.Information);
if (dr == DialogResult.Yes)
{
XMLControl control
= (XMLControl)sender;
XmlNode delNode
= this.FindeNodeByName(control.Stuname);
if (delNode != null)
{
XmlNode root
= xmldoc.SelectSingleNode("root");
root.RemoveChild(delNode);
//移除
}
xmldoc.Save(
"Config.xml");
this.RefreshControl();
}
}

void control_ModiEvent(object sender, EventArgs e)
{
XMLControl control
= (XMLControl)sender;
XmlNode modiNode
= this.FindeNodeByName(control.Stuname);
modiNode[
"name"].InnerText = control.Stuname;
modiNode[
"age"].InnerText = control.Age.ToString();
modiNode[
"phone"].Attributes["num"].InnerText = control.Phone;
xmldoc.Save(
"Config.xml");
this.RefreshControl();
}

private bool Exist(string name)
{
XmlNode root
= xmldoc.SelectSingleNode("root");
XmlNodeList list
= root.SelectNodes("student");
foreach(XmlNode node in list)
{
if (name == node["name"].InnerText)
{
return true;
}
}
return false;
}

private XmlNode FindeNodeByName(string name)
{
XmlNode root
= xmldoc.SelectSingleNode("root");
XmlNodeList list
= root.SelectNodes("student");
foreach (XmlNode node in list)
{
if (node["name"].InnerText == name)
return node;
}
return null;
}

private void Form1_Load(object sender, EventArgs e)
{
this.RefreshControl();
}

}

(三) 呵呵下面还有一个更厉害的“导航试搜索”XPathNavigator 提供了强大的编辑、查找、替换、遍历xml的功能。
,其还提供了类似于 Regex 、Excel公式模式去操作xml,很强大哦。

导航
public partial class Form1 : Form
{
private XmlDocument doc;
private XPathNavigator nav;

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
nav.MoveToRoot();
//移动到根节点

nav.MoveToFirst();
//移动到当前节点的同级的第一个节点

nav.MoveToFirstChild();
//移动到第一个子节点

nav.MoveToFirstChild();
//移动到第一个子节点

nav.MoveToNext();
//移动到下一个同级节点

MessageBox.Show(
"nav.Name : " + nav.Name,"信息提示",MessageBoxButtons.OK,MessageBoxIcon.Information);

nav.MoveToChild(
"age","");

MessageBox.Show(
"第二个student的 age : " + nav.ValueAsInt, "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

nav.MoveToNext();

nav.MoveToAttribute(
"num","");

MessageBox.Show(
"phone num 属性" + nav.Value , "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

nav.MoveToParent();
//移动到当前的父节点

MessageBox.Show(nav.OuterXml,
"信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

private void Form1_Load(object sender, EventArgs e)
{
doc
= new XmlDocument();
doc.Load(
"Config.xml");
nav
= doc.CreateNavigator();
}

private void button4_Click(object sender, EventArgs e)
{
nav.MoveToRoot();
string expression = "sum(/root/student/age) div count(/root/student/age)";
double result = (double)nav.Evaluate(expression);
MessageBox.Show(result.ToString() ,
"信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

}

private void button3_Click(object sender, EventArgs e)
{
nav.MoveToRoot();
string expression = "./root/student/name[../age > 15]";
XPathNodeIterator it
= nav.Select(expression );
while (it.MoveNext())
{
MessageBox.Show(it.Current.Value,
"信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}

private void button2_Click(object sender, EventArgs e)
{
nav.MoveToRoot();
string expression = "./root/student/phone[@num='7777']";

XPathNodeIterator it
= nav.Select(expression );
while (it.MoveNext())
{
XPathNavigator temp
= it.Current;// 把当前游标赋值一个新游标
temp.MoveToParent();

temp.MoveToChild(
"name", "");
MessageBox.Show(temp.Value,
"信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}

(四)xml 与 类实例之间的序列化与反序列化

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
Root root
= new Root();
Student s
= new Student();
s.Age
= 15;
s.Name
= "孟庆雨";
s.phone
= new Phone();
s.phone.Num
= "0311-7260311";
root.Students.Add(s);

s
= new Student();
s.Age
= 25;
s.Name
= "孟庆雨2";
s.phone
= new Phone();
s.phone.Num
= "0311-7260000";
root.Students.Add(s);

XmlSerializer xmlser
= new XmlSerializer(typeof(Root));
XmlTextWriter xmlw
= new XmlTextWriter("my.xml", Encoding.Default);
xmlser.Serialize(xmlw, root);
xmlw.Close();

StringBuilder sb
= new StringBuilder();
StringWriter sw
= new StringWriter(sb);
xmlser.Serialize(sw, root);
MessageBox.Show(sb.ToString());

MessageBox.Show(
"反序列化");
StringReader sr
= new StringReader(sb.ToString());
Root r
=(Root) xmlser.Deserialize(sr);
foreach (Student stu in r.Students)
{
string str = stu.Name + " : " + stu.Age + " : " + stu.phone.Num;
MessageBox.Show(
"姓名 : 年龄 : 电话号码\n" + str);
}
MessageBox.Show(
"反序列化完毕");


MemoryStream ms
= new MemoryStream();
xmlw
= new XmlTextWriter(ms, Encoding.UTF8);
xmlser.Serialize(xmlw, root);
MessageBox.Show(Encoding.UTF8.GetString(ms.ToArray()));

}

private void button2_Click(object sender, EventArgs e)
{
XmlSerializer xmlser
= new XmlSerializer(typeof(Root));
FileStream fs
= new FileStream("my.xml",FileMode.Open);
Root root
= (Root)xmlser.Deserialize(fs);
foreach (Student s in root.Students)
{
string str = s.Name + " : " + s.Age + " : " + s.phone.Num;
MessageBox.Show(
"姓名 : 年龄 : 电话号码\n" + str);
}

}
}

呵呵 差不多了 就这些了。

新年的后的第一次总结、祝愿所有人:一切“兔”飞猛进。

posted @ 2011-02-12 16:40  把爱延续  阅读(621)  评论(1编辑  收藏  举报