XElement xperson = new XElement("person");//根节点
xperson.SetAttributeValue("age", 30);//设置属性
XElement xperson1 = new XElement("person1");
xperson1.Value = "tom";//设置 innerText值
xperson1.SetAttributeValue("sex", "男");
XElement xperson2 = new XElement("person2");
xperson.Add(xperson1);//加入到根结点
xperson.Add(xperson2);
string xml = xperson.ToString();
Console.WriteLine(xml);
using (Stream stream = File.OpenWrite(@"D:\1.xml"))
{
byte[] bytes = new byte[1024];
bytes = Encoding.UTF8.GetBytes(xml);
stream.Write(bytes, 0, bytes.Length);//写入文件
}
2.读取XML文件
----------如何读取xml文件的内容----------------
using(Stream stream=File.OpenRead(@"D:\1.xml"))
{
using(StreamReader reader= new StreamReader(stream))
{
//从Reflector从可以看到TextReader的子类是StreamReader所以,可以直接用StreamReader来读取XML文档,传给XDocument.Load方法
XDocument xml=XDocument.Load(reader);//load里面
Console.WriteLine( xml.Root.ToString());//xml文档
Console.WriteLine(xml.Root.Nodes().ElementAt(0).ToString());//ElementAt()第几个子节点
Console.WriteLine(xml.Root.Attribute("age").Value);//返回根节点的属性的值
XNode nodes=xml.Root.Nodes().ElementAt(0);
XElement e=nodes as XElement;
Console.WriteLine(e.Attribute("sex").Value);//读取第一个子节点的属性
}
}
3.读取App.Config
using (Stream stream = File.OpenRead(@"D:\net实例教程\练习net\XML练习\XML练习\App.config"))
{
using (StreamReader reader = new StreamReader(stream))
{
XDocument xml = XDocument.Load(reader);
XNode n1 = xml.Root.Nodes().ElementAt(0);//这就是<configuration> ------下面----<connectionStrings>
XElement e1 = n1 as XElement;
XNode n1_1 = e1.Nodes().ElementAt(0);//connectionStrings下面的<add .....>第一个
XNode n1_2 = e1.Nodes().ElementAt(1);//connectionStrings下面的<add .....>第一个
XElement e1_1 = n1_1 as XElement;
XElement e1_2 = n1_2 as XElement;
//Console.WriteLine("Name={0},Connection={1}", e1.Attribute("name").Value, e1.Attribute("connectionString").Value);
Console.WriteLine("第一个连接字符串的name={0},Connection={1}", e1_1.Attribute("name"), e1_1.Attribute("connectionString"));
Console.WriteLine("第一个连接字符串的name={0},Connection={1}", e1_2.Attribute("name"), e1_2.Attribute("connectionString"));
}
}
using (Stream stream = File.OpenRead(@"D:\net实例教程\练习net\XML练习\XML练习\App.config"))
{
using (StreamReader reader = new StreamReader(stream))
{
XDocument xml=XDocument.Load(reader);
IEnumerable<XElement> XConnstr = xml.Root.Elements("connectionStrings");
Console.WriteLine(XConnstr.Count().ToString());
if (XConnstr.Count() == 1)
{
XElement Connstr = XConnstr.ElementAt(0);
foreach(XElement conn in Connstr.Elements("add"))
{
string name = conn.Attribute("name").Value;
string Connection = conn.Attribute("connectionString").Value;
Console.WriteLine("Name={0},Age={1}", name, Connection);
}
}
}
}