您的位置:首页 > 编程语言 > C#

c# 解析Xml文件

2013-04-19 12:07 225 查看
c# Xml解析类和应用

这是面向对象的课程设计作业,就是自己写xml解析类并且完成由xml文件向图形的转化。

这里用了两种方法,第一种是c#自己提供的xml解析函数,第二种是自己的xml解析函数。

xml解析函数(原创)

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.IO;

namespace WindowsFormsApplication1

{

public class xmlParser

{

string s = null;

string temp;

bool isnull = false;

byte[] byteArray = new byte[1];

Stack<TreeNode> nodeStack = new Stack<TreeNode>();

List<string> contents = new List<string>();

bool newline = false;

public TreeNode xmlParse(string addr)

{

TreeNode elemNode = new TreeNode();

FileStream f = new FileStream(addr, FileMode.Open, FileAccess.Read);

while (isnull == false)

{

int i = f.Read(byteArray, 0, 1);

temp =System.Text.Encoding.Default.GetString(byteArray);

if (i < 1)

{

isnull = true;

break;

}

if (temp == null)

{

break;

}

if (newline == true &&temp == " ")

{

continue;

}

if (temp == " " ||temp == "\r" || temp == ">" || temp == "\n")

{

if (s.Contains('<')&& !s.Contains('/'))

{

//元素 1

string[] t =s.Split('<');

TreeNode tn1 = newTreeNode();

tn1.Text = t[1];

tn1.Tag = 1;

if (nodeStack.Count >0)

{

nodeStack.Peek().Nodes.Add(tn1);

}

else

{

elemNode = tn1;

}

nodeStack.Push(tn1);

s = "";

}

else if (s.Contains('/'))

{

//文本节点 3

string[] t =s.Split('/');

string[] t1 =t[0].Split('<');

if (t1[0] !="")

{

contents.Add(t1[0]);

TreeNode tn3 = newTreeNode();

tn3.Text = t1[0];

tn3.Tag = 3;

nodeStack.Peek().Nodes.Add(tn3);

}

s = "";nodeStack.Pop();

}

else if (temp =="\n")

{

s = "";

newline = true;

}

else if (temp =="\r" || s == null || s == " ")

{

s = "";

}

else

{

//属性节点 2

string s2 = s.Insert(0,"@");

contents.Add(s2);

TreeNode tn2 = newTreeNode();

tn2.Text = s2;

tn2.Tag = 2;

nodeStack.Peek().Nodes.Add(tn2);

s = "";

s2 = "";

}

}

else

{

s += temp;

newline = false;

}

}

isnull = false;

f.Close();

return elemNode;

}

}

}

思路:这里只用了一个栈,基本思路就是不断的一个字符一个字符读取,当遇到特殊字符的时候,判断,如果是节点例如<A>那么就进栈作为父节点,然后所有的属性都算成是子节点,如果在</a>之前又有了新的节点,那么也是<a>的子节点,以此一直向下读取,然后写入到树结构中,这里的树结构利用的是c#自带的。

然后就是绘图,程序结构是



每个节点都是一个类,并继承treenode类,然后有个节点管理类主要负责节点的管理,保存所有的节点,对位置,内容等进行管理。



还有个画图类,和画图管理类,主要是对picturebox中的画图进行管理,绘制节点管理中的所有节点。

然后就完成了。】



应用程序源代码稍后传上来。下载地址:http://download.csdn.net/detail/bjut_yue/5276322

点击打开链接
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: