C# 对XML的操作 具体一点是对.config

来源:百度知道 编辑:UC知道 时间:2024/05/22 00:20:17
<?xml version="1.0" encoding="utf-8"?>
<baserk>
<!--【成都最新楼盘】楼盘id号与名称-->
<NewestHouse>
<No1 id="378" name="锦江城市花园 " />
<No2 id="79" name="恒大绿洲" />
<No3 id="78" name="华润翡翠城 " />
<No4 id="477" name="华润二十四城 " />
<No5 id="60" name="成都华侨城纯水岸" />
<No6 id="27" name="龙湖三千城" />
</NewestHouse>
</baserk>

读取的代码我已经知道了
XmlDocument doc = new XmlDocument();
doc.Load(System.Web.HttpContext.Current.Server.MapPath(filepath));
XmlNode xnuser = doc.SelectSingleNode(node);
if (n <= 0)
{
return Convert.ToString(xnuser.Attributes[attribute].Value);
}
else
{
return getcharabs(Convert.ToString(xnuser.Attributes[attribute].Value),n);
}

请教修改和插入 重点是修改

xnuser.Attributes[attribute].Value = "aasdfasd"; 这个就是修改
修改以后保存
doc.Save(filepath);
添加一个属性
attr = doc.CreateAttribute(attributeName);
attr.Value = value;
node.Attributes.SetNamedItem(attr);
添加一个节点
XmlNode row = doc.CreateNode("element", "row", "");
data.AppendChild(row);

doc.Select("/baserk/NewestHouse"); //选择xPath

获得一个节点,然后新建一个Node,设置好Attribute,再添加到下面。
定位要正确,插入应该不是问题。

自己去查一下msdn。

static void XmlEdit()
{
string file = @"c:\a.xml";
XmlDataDocument doc = new XmlDataDocument();
doc.Load(file);
//查询,路径用 / 比如你的<NewestHouse> 里面有一个属性 <NewestHouse id=2>那么应该写成
//XmlNode node = doc.SelectSingleNode("baserk/NewestHouse[@id=2]");你这里没有属性就不需要这样
//, 查询用[]括起来,属性值用 @属性名=value 如果是内容的话用 点就行 [.=1