如何操作XML文件中的内容?自己用于测试的写了一些,请大家补充完整:
private void Page_Load(object sender, System.EventArgs e)
{
string xmlpath=Server.MapPath("xmlfile/users.xml");
if(IsPostBack) //回滚
{
//初始化一个XML文件:元素就是节点
XmlDocument xmldoc=new XmlDocument();
xmldoc.AppendChild(xmldoc.CreateProcessingInstruction("xml","version=1.0 encoding=gb2312"));//定义头部
XmlNode node=xmldoc.AppendChild(xmldoc.CreateElement("users"));//添加DocumentElement
xmldoc.AppendChild(node);//添加节点
XmlAttribute att=xmldoc.CreateAttribute("descrption");
att.Value="注册用户信息文件";
((XmlElement)node).SetAttributeNode(att);//设置元素的属性
//文档元素DocumentElement添加子节点的方法
node.AppendChild(node.AppendChild(xmldoc.CreateElement("子节点测试")));//添加节点
string xmlfilepath=xmlpath;
if(File.Exists(xmlfilepath))
File.Delete(xmlfilepath);
XmlTextWriter writer=new XmlTextWriter(xmlfilepath,System.Text.Encoding.GetEncoding("gb2312"));//null
writer.Formatting=Formatting.Indented;//根据元素的层次进行缩进(也就是排版)
writer.Indentation=1;//将层次中的每个级别缩进多少个单位
writer.IndentChar='\t';//缩进的字符进隔字符号.用一个Tab键所占空白字符
xmldoc.WriteTo(writer);//将一个XML文件字符写进文件.
writer.Close(); //写完后关闭
}
else //第一次打开网页时
{
XmlDocument xmldoc=new XmlDocument();
xmldoc.LoadXml(xmlpath);//为什么会加载错误呢? 根级别上的数据无效。 行 1,位置 1。
XmlNode node=xmldoc.SelectSingleNode("/users").ChildNodes[1];
addr.Text=node.Attributes["addr"].Value;//赋值给一文本框
name.Text=node.Name;//赋值给一文本框
xmldoc.Save(xmlpath);
/*
Server.HTMLencode(node.ChildNodes[1].InnerText);
node.Attributes.Count;node.Attributes[0].Name;node.Attributes[0].Value;
XmlNodeList nodes = doc.SelectNodes( "/configuration/appSettings/add" );//选择所有所appSettings子结点子add名字开头头的的节点.
foreach( XmlNode node in nodes )
{
if(node.Attributes["key"].Value=="SystemMessage")//设置系统消息
node.Attributes[ "value" ].Value=SystemMessageContent.Text;
}
<?xml version="1.0" encoding="gb2312"?>
<users 描述="注册用户信息文件">
<subnode />
<weddingin2008 id="1" name="李政" sex="男士" addr="岳阳华容东山" homepage="http://www.yueyan.com" email="www.yueyan.com@tom.com" qq="53486992" subject="打工者的天堂网站成功" content="欢迎大家来做客" sendreply="1"/>
</users>
*/
}
}