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

C#读取XML文件数据和把数据保存至xml的方法

2015-09-29 14:44 1301 查看
原文在百度知道中,来源于多个网友。

新浪微博:http://blog.sina.com.cn/s/blog_ad7fd0f4010180md.html

(一)

保存

var xml =XElement.Load(@"路径");

xml.Element("节点名字").AddAfterSelf(new XElement("节点名字","要添加的值"));

xml,Save(@"路径");

读取

var xml =XElement.Load(@"路径");

如果是属性

var query=xml.Element().Where(n=>n.Attribute("比较的节点名字").Value=="名字")

.Select(n=>n.Attribute("要获取的节点名字").Value).Frist();

如果是值

var query=xml.Element().Where(n=>n.Value=="名字")

.Select(n=>n.Value).Frist();

(二)

直接用项目里面的app.config或是web.config最方便。

在里面的appSettings段里加一个元素:

<appSettings>

<add key="mypath" value="thepath"/>

</appSettings>

可以直接用ConfigurationManager读取:

string pathStr = ConfigurationManager.AppSettings["mypath"].ToString();;

(三)

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

//需要添加的

using System.Xml;

using System.IO;

namespace xml

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

#region 加载窗体,加载数据

private void Form1_Load(object sender, EventArgs e)

{

getFromXml();

}

#endregion

//变量声明

string username;

string password;

string path = @"config.xml";

//保存设置

private void button1_Click(object sender, EventArgs e)

{

username = textBox1.Text;

password = textBox2.Text;

saveToXml(username,password);

MessageBox.Show("保存成功");

}

#region 把数据保存至xml文件

/// <summary>

/// 保存至xml文件

/// </summary>

/// <param name="username">账号</param>

/// <param name="password">密码</param>

private void saveToXml(string username,string password)

{

XmlDocument xmlDoc = new XmlDocument();

xmlDoc.Load(path);

XmlNode node;

node = xmlDoc.SelectSingleNode("config/username");

if (node == null)

{

XmlElement n = xmlDoc.CreateElement("username");

n.InnerText = username;

xmlDoc.SelectSingleNode("config").AppendChild(n);

}

else

{

node.InnerText = username;

}

node = xmlDoc.SelectSingleNode("config/password");

if (node == null)

{

XmlElement n = xmlDoc.CreateElement("password");

n.InnerText = password;

xmlDoc.SelectSingleNode("config").AppendChild(n);

}

else

{

node.InnerText = password;

}

xmlDoc.Save(path);

}

#endregion

#region 从xml获得数据,并加载

private void getFromXml()

{

//获得数据

XmlDocument xmlDoc = new XmlDocument();

xmlDoc.Load(path);

XmlNode node;

node = xmlDoc.SelectSingleNode("config/username");

username = node.InnerText;

node = xmlDoc.SelectSingleNode("config/password");

password = node.InnerText;

//加载数据

textBox1.Text=username;

textBox2.Text=password;

}

#endregion

}

}

=======================

<?xml version="1.0" encoding="utf-8"?>

<config>

<username>king</username>

<password>123456</password>

</config>

如果config.xml格式正确

会提示

缺少根元素

更改一致就可以了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: