首页 > 代码库 > ASP.NET操作XML
ASP.NET操作XML
1.c#创建xml文档
class Program
{
static void Main(string[] args)
{
XElement element = new XElement("Person");
XElement element1 = new XElement("son1");
XElement element2 = new XElement("son2");
element.SetAttributeValue("type", "人类");
element1.SetAttributeValue("age", 15);
element1.SetValue("张三");
element.Add(element1);
element.Add(element2);
string strxml= element.ToString();
Console.WriteLine(strxml);
Console.ReadLine();
}
}
2.c#读取xml文档
xml文档如下:
<?xml version="1.0" encoding="utf-8"?>
<person>
<men>
<men1 age="25">
张三
</men1>
<men2 age="15">
李四
</men2>
</men>
<women>
<women1 age="25">
小丽
</women1>
<women2 age="19">
咪咪
</women2>
</women>
</person>
c#代码如下:
using (Stream stream = File.OpenRead(@"D:\完成项目\2014-3-14\kongzhitai\xml\xml\xml.xml"))
{
using (StreamReader reader = new StreamReader(stream))
{
XDocument doc = XDocument.Load(reader);
int count = doc.Root.Elements().Count();
foreach (var element1 in doc.Root.Elements())
{
foreach (var element2 in element1.Nodes())
{
if(element2.GetType()==typeof(XElement))
{
XElement ele = (XElement)element2;
Console.WriteLine("姓名:"+ele.Value+"年龄:"+ele.Attribute("age").Value);
}
}
}
}
}