c#操作xml文件

2018-06-17 20:06:05来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;


namespace delegatedemo
{
public class XmlClass
{
private string xmlPath;
public XmlClass(string xmlPath)
{
this.xmlPath = xmlPath;
}


public DataView GetXmlElement()
{
DataTable myTable = new DataTable();

DataRow myRow;
myTable.Columns.Add("学号");
myTable.Columns.Add("姓名");
myTable.Columns.Add("年龄");
myTable.Columns.Add("性别");
XmlDocument doc = new XmlDocument();
doc.Load(xmlPath);
XmlElement xmlElement = doc.DocumentElement;
foreach (XmlNode node in xmlElement.ChildNodes)
{
string number = node.Attributes["number"].Value;
string age = node.SelectSingleNode("Age").InnerText;
string name = node.SelectSingleNode("Name").InnerText;
string sex = node.SelectSingleNode("Sex").InnerText;
myRow = myTable.NewRow();
myRow["学号"] = number;
myRow["姓名"] = name;
myRow["性别"] = sex;
myRow["年龄"] = age;
myTable.Rows.Add(myRow);
}
return myTable.DefaultView;
}


public void InsertXml()
{
XmlDocument doc = new XmlDocument();
doc.Load(xmlPath);
XmlElement root = doc.DocumentElement;
XmlElement student = doc.CreateElement("student");
student.SetAttribute("number", "003");
XmlElement name = doc.CreateElement("name");
name.InnerText = "张三";
XmlElement age = doc.CreateElement("age");
age.InnerText = "21";
XmlElement sex = doc.CreateElement("sex");
sex.InnerText = "女";
root.AppendChild(student);
root.AppendChild(name);
root.AppendChild(age);
root.AppendChild(sex);
doc.Save(xmlPath);
}
}
}

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:C# 的界面控件属性修改线程安全问题

下一篇:当前标识(IIS APPPOOL\dfcreport)没有对“C:\Windows\Microsoft.