c#操作xml(读,写)

c#读xml文件:

//不用说,是建立对象,读取文件
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("haha.xml");
//获取bookstore节点的所有子节点
XmlNodeList nodeList = xmlDoc.SelectSingleNode("conf").ChildNodes;
//有多少个子节点
int configNum = nodeList.Count;
//遍历所有子节点
foreach (XmlNode fir1 in nodeList)
{
    //将子节点类型转换为XmlElement类型
    XmlElement xmle = (XmlElement)fir1;
    //同上,再遍历一遍,如果下面还有子节点,层层遍历
    XmlNodeList nodeList2 = xmle.ChildNodes;
    foreach (XmlNode fir2 in nodeList2)
    {
        if (fir2.Name == "ipaddress")
        {
           //你的变量 = fir2.InnerText.ToString();
        }
        if (fir2.Name == "ipname")
        {
            //你的变量 = fir2.InnerText.ToString();
        }
    }
}
//xmle声明下面也可以加入这句,代表取属性为id的节点
if (xe.GetAttribute("id") == 你的参数)
///使用完后可以返回个数组。 

上面的代码稍微修改一下,就可以用作修改xml了,很简单:

//开头都一样到了下面要注意
//xmle声明下面也可以加入这句,代表取属性为id的节点
if (xe.GetAttribute("id") == 你的参数)
{
    foreach (XmlNode fir1 in nodeList)
    {
        XmlElement xmle = (XmlElement)fir1;
        XmlNodeList nodeList2 = xmle.ChildNodes;
        foreach (XmlNode fir2 in nodeList2)
        {
            if (fir2.Name == "ipaddress")
            {
                //注意,这里改了fir2.InnerText = 你的变量;
            }
        }
    }
    break;
}
//最后不要忘记保存。
xmlDoc.Save("ping.xml");
posted @ 2010-09-19 14:14  巴拉则器  阅读(348)  评论(1编辑  收藏  举报
www.blazeq.cn