C#对XML完整操作
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#对XML完整操作相关的知识,希望对你有一定的参考价值。
<?xml version="1.0"?>
<birthday>
<NO1>
<type>类型</type>
<date>时间</date>
<title>信息</title>
<name>姓名</name>
</NO1>
<NO2>
<type>类型</type>
<date>时间</date>
<title>信息</title>
<name>姓名</name>
</NO2>
</birthday>
1.XML数据格式如上,要求程序有读.写.编辑.删除操作
2.请尽可能帮忙写备注
3.xml数据读入到treeview中,分别显示各个字段,并按时间顺序排序
4.请不要复制网上代码,很多都是出现杂七杂八问题呢
5.代码请尽量简洁
6.如果好用,再加感谢分^_^
=======================bookstore.XML内容====================
<?xml version="1.0" encoding="gb2312"?>
<bookstore>
<book>
</book>
<book>
</book>
<book genre="李赞红" ISBN="2-3631-4">
<title>CS从入门到精通</title>
<author>候捷</author>
<price>58.3</price>
</book>
<book genre="李赞红" ISBN="2-3631-4">
<title>CS从入门到精通</title>
<author>候捷</author>
<price>58.3</price>
</book>
</bookstore>
=======================读取========================
XmlDocument doc = new XmlDocument();
doc.Load(@"d:\bookstore.xml");
XmlElement root = doc.DocumentElement;
MessageBox.Show(root.SelectNodes("book")[0].InnerText);
=======================添加=========================
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@"d:\bookstore.xml");
XmlNode root = xmlDoc.SelectSingleNode("bookstore");//查找<bookstore>
XmlElement xe1 = xmlDoc.CreateElement("book");//创建一个<book>节点
xe1.SetAttribute("genre", "李赞红");//设置该节点的genre属性
xe1.SetAttribute("ISBN", "2-3631-4");//设置该节点的ISBN属性
XmlElement xesub1 = xmlDoc.CreateElement("title");//添加一个名字为title的子节点
xesub1.InnerText = "CS从入门到精通";//设置文本
xe1.AppendChild(xesub1);//把title添加到<book>节点中
XmlElement xesub2 = xmlDoc.CreateElement("author");
xesub2.InnerText = "候捷";
xe1.AppendChild(xesub2);
XmlElement xesub3 = xmlDoc.CreateElement("price");
xesub3.InnerText = "58.3";
xe1.AppendChild(xesub3);
root.AppendChild(xe1);//把book添加到<bookstore>根节点中
xmlDoc.Save(@"d:\bookstore.xml");
======================修改========================
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@"d:\bookstore.xml");
XmlNodeList nodeList = xmlDoc.SelectSingleNode("bookstore").ChildNodes;//获取bookstore节点的所有子节点
foreach (XmlNode xn in nodeList)//遍历所有名字为bookstore的子节点
XmlElement xe = (XmlElement)xn;//将子节点类型转换为XmlElement类型
if (xe.GetAttribute("genre") == "李赞红")//如果genre属性值为“李赞红”
xe.SetAttribute("genre", "update李赞红");//则修改该属性为“update李赞红”
XmlNodeList nls = xe.ChildNodes;//继续获取xe(xn)子节点的所有子节点
foreach (XmlNode xn1 in nls)//遍历
XmlElement xe2 = (XmlElement)xn1;//转换类型
if (xe2.Name == "author")//如果找到
xe2.InnerText = "亚胜";//则修改
break;//找到退出来
break;
xmlDoc.Save(@"d:\bookstore.xml");//保存。
========================删除=========================
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@"d:\bookstore.xml");
XmlNodeList xnl = xmlDoc.SelectSingleNode("bookstore").ChildNodes;
foreach (XmlNode xn in xnl)
XmlElement xe = (XmlElement)xn;
if (xe.GetAttribute("genre") == "fantasy")
xe.RemoveAttribute("genre");//删除genre属性
else if (xe.GetAttribute("genre") == "update李赞红")
xe.RemoveAll();//删除该节点的全部内容
xmlDoc.Save(@"d:\bookstore.xml"); 参考技术A //假定TreeView控件的id为treeView
XmlDocument dom = new XmlDocument();
dom.Load("aaa.xml");//装载XML文档
//遍历所有节点
int num = 0;
foreach(XmlElement birthday in dom.DocumentElement.ChildNodes)
//读取数据
string type = birthday.SelectSingleNode("type").InnerText;
string date = birthday.SelectSingleNode("date").InnerText;
string title = birthday.SelectSingleNode("title").InnerText;
string name = birthday.SelectSingleNode("name").InnerText;
string text = name + ":" + title;//节点文字
string image = type;//节点图片
string data = num.ToString();//节点对应数据
num++;
//装载示例,将新建的节点添加到TreeView
TreeNode node = new TreeNode(text, data, image);//create a new node
treeView.Nodes.Add(node);
//编辑示例:将当前节点的生日更改为当前日期
birthday.SelectSingleNode("date").InnerText = DateTime.Now.ToString();
//删除示例:将当前节点删除
birthday.ParentNode.RemoveChild(birthday);
dom.Save();本回答被提问者采纳 参考技术B 方法一 :使用XML控件
<% @ Page Language="C#"%>
<html>
<body>
<h3><font face="Verdana">读取XML方法一</font></h3>
<from runat=server>
<asp:Xml id="xml1" DocumentSource="grade.xml" runat="server" />
</from>
</body>
</html>
方法二: 使用DOM技术
<% @ Page Language="C#"%>
<% @ Import Namespace="System.Xml"%>
<% @ Import Namespace="System.Xml.Xsl"%>
<html>
<script language="C#" runat="server">
void Page_Load(Object sender,EventArgs e)
XmlDocument doc=new XmlDocument();
doc.Load(Server.MapPath("grade.xml"));
xml1.Document=doc;
</script>
<body>
<h3><font face="Verdana">读取XML方法二</font></h3>
<from runat=server>
<asp:Xml id="xml1" runat="server" />
</from>
</body>
</html>
方法三 :使用DataSet对象
<% @ Page Language="C#"%>
<% @ Import Namespace="System.Data"%>
<% @ Import Namespace="System.Data.OleDb"%>
<script language="C#" runat="server">
void Page_Load(Object sender,EventArgs e)
DataSet objDataSet=new DataSet();
objDataSet.ReadXml(Server.MapPath("grade.xml"));
dgEmployees.DataSource=objDataSet.Tables["student"].DefaultView;
dgEmployees.DataBind();
</script>
<body>
<h3><font face="Verdana">读取XML方法三</font></h3>
<asp:DataGrid id="dgEmployees" runat="server" />
</body>
</html>
方法四 :按文本方式读取
<% @ Page Language="C#"%>
<% @ Import Namespace="System.Xml"%>
<html>
<script language="C#" runat="server">
private void Page_Load(Object sender,EventArgs e)
XmlTextReader objXMLReader=new XmlTextReader(Server.MapPath("grade.xml"));
string strNodeResult="";
XmlNodeType objNodeType;
while(objXMLReader.Read())
objNodeType =objXMLReader.NodeType;
swith(objNodeType)
case XmlNodeType.XmlDeclaration:
//读取XML文件头
strNodeResult+="XML Declaration:<b>"+objXMLReader.Name+""+objXMLReader.Value+"</b><br/>";
break;
case XmlNodeType.Element:
//读取标签
strNodeResult+="Element:<b>"+objXMLReader.Name+"</b><br/>";
break;
case XmlNodeType.Text:
//读取值
strNodeResult+=" -Value:<b>"+objXMLReader.Value+"</b><br/>";
break;
//判断该节点是否有属性
if(objXMLReader.AttributeCount>0)
//用循环判断完所有节点
while(objXMLReader.MoveToNextAttibute)
//取标签和值
strNodeResult+=" -Attribute:<b>"+objXMLReader.Name+"</b> value:<b>"+objXMLReader.Value+"</b><br/>";
LblFile.Text=strNodeResult;
</script>
<body>
<h3><font face="Verdana">读取XML方法四</font></h3>
<from runat=server>
<asp:label id="LblFile" runat="server" />
</from>
</body>
</html> 参考技术C foshie
c#对xml的操作
操作xml可以通过XElement对象,比较方便的使用列举以下几点:
把字符串转变成XElement,保存成xml文件,加载xml文件:
//把字符串解析成XElement对象 string str = "<students><student><name>one</name></student><student><name>two</name></student><student><name>three</name></student></students>"; var xml = XElement.Parse(str); //保存文件 xml.Save("1.xml"); Console.WriteLine("保存成功"); //读取文件 xml = XElement.Load("1.xml"); Console.WriteLine(xml);
集合创建XElement对象
class Program { static void Main(string[] args) { List<Person> list = new List<Person>() { new Person(){Id=1,Name="张三"}, new Person(){Id=2,Name="李四"}, new Person(){Id=3,Name="王五"}, new Person(){Id=4,Name="赵六"}, new Person(){Id=5,Name="钱七"} }; var xml = new XElement("Persons", list.Select(x => new XElement("name",x.Name))); Console.WriteLine(xml); } } public class Person { public int Id { get; set; } public string Name { get; set; } }
2 、使用lamda查询xml值
xml文件如下:
<?xml version="1.0" encoding="utf-8" ?> <AOnlineOrg> <eSales> <Member SortNo="1"> <Login>GUOXIN</Login> <PositionID>1-25ISRB</PositionID> <UserID>1-25ISRQ</UserID> <BU>ICSF</BU> </Member> <Member SortNo="2"> <Login>LIUXIANG</Login> <PositionID>1-196945</PositionID> <UserID>1-19694A</UserID> <BU>ICSF</BU> </Member> <Member SortNo="3"> <Login>QINYANG</Login> <PositionID>1-10DAMN</PositionID> <UserID>1-KJ3IA</UserID> <BU>ICSF</BU> </Member> <Member SortNo="4"> <Login>XIAOCANFU</Login> <PositionID>1-FKZUJF</PositionID> <UserID>1-FKZUB5</UserID> <BU>ICSF</BU> </Member> <Member SortNo="5"> <Login>XIAOHUAHU</Login> <PositionID>1-JWZ3R</PositionID> <UserID>1-JWZ4F</UserID> <BU>ICSF</BU> </Member> <Member SortNo="6"> <Login>MANWEIZHAO</Login> <PositionID>1-JDSX2</PositionID> <UserID>1-1U5P9V</UserID> <BU>IAG</BU> </Member> <Member SortNo="7"> <Login>LIJUANNIU</Login> <PositionID>1-IABTN</PositionID> <UserID>1-1PW39I</UserID> <BU>IAG</BU> </Member> <Member SortNo="8"> <Login>QUANFANGZHOU</Login> <PositionID>1-H1MFS</PositionID> <UserID>1-ISATTR</UserID> <BU>IAG</BU> </Member> <Member SortNo="9"> <Login>FENGYUANLI</Login> <PositionID>1-DHZB5</PositionID> <UserID>1-DI7M2</UserID> <BU>IAG</BU> </Member> </eSales> </AOnlineOrg>
上面xml文件保存为1.xml,查找其Member的属性SortNo的值小于3的Login值:
//加载 var xml = XElement.Load("1.xml"); //选择集合 var list = xml.Descendants("Member"); //查找xml中Member的属性SortNo的值小于3的Login值 var arr = list.Where(x => ((int)x.Attribute("SortNo")) < 3).Select(x => x.Element("Login")); foreach (var item in arr) { Console.WriteLine(item); }
查找所有Login值
var xml = XElement.Load("1.xml"); //查找所有Login值 foreach (var item in xml.Descendants("Login")) { Console.WriteLine(item.Value); }
把xml转成类对象集合
public class Person { public int SortNo { get; set; } public string Login { get; set; } public string PositionID { get; set; } public string UserID { get; set; } public string BU { get; set; } }
var xml = XElement.Load("1.xml"); List<Person> list = new List<Person>(); foreach (var item in xml.Descendants("Member")) { if (item.HasElements) { list.Add(new Person { Login = item.Element("Login").Value, PositionID = item.Element("PositionID").Value, UserID = item.Element("UserID").Value, BU = item.Element("BU").Value, SortNo = (int)item.Attribute("SortNo") }); } } foreach (var item in list) { Console.WriteLine(item.Login); }
以上是关于C#对XML完整操作的主要内容,如果未能解决你的问题,请参考以下文章