以下是xml文件的一个节点,我想修改<Name>小王</Name><Name>小张</Name>,该怎么修改呢,我写了一种方法,有两个循环,感觉代码有些麻烦,所以请大家给个指点啊,谢谢了<Persons>
<Person>
    <ID>12345678</ID>
    <Name>小王</Name>
    <Department>技术中心</Department>
    <Position>职员</Position>
    <Password>12345678</Password>
    <Group>项目</Group>
    <Action>设计</Action>
  </Person>
.....
.....
</Persons>

解决方案 »

  1.   

    XmlDocument doc; //自己打开foreach(XmlNode item in doc["Persons"].SelectNodes["Person"])
    {
       if(item["ID"].InnerText == "12345678")item["Name"].InnerText = "小张";
    }xml菜鸟...
      

  2.   

    一、
    XmlDocument dc;
            XmlNodeList xnl = dc.GetElementsByTagName("Name");
            for (int i = 0; i < xnl.Count; i++)
            {
                if (xnl[i].InnerText == "小王")
                {
                    xnl[i].InnerText = "小张";
                }
            }
            //保存
      

  3.   

    XmlDocument xml=new XmlDocument(); 
    xml.LoadXml(文档载入); 
    XmlElement root=xml.DocumentElement; 
    XmlNodeList nodes=root.GetElementsByTagName("Person"); 
    for(int i=nodes.Count-1;i>=0;i--) 

    if(nodes[i].ChildNodes[1].InnerText=="小王") //我觉得判断id比较好

       nodes[i].ChildNodes[1].InnerText="小张";
    } }
      

  4.   

    二、
    直接string替换
    string xmlstr;
    xmlstr = xmlstr.Replace("<Name>小王 </Name>","<Name>小张 </Name>");
      

  5.   

    充分利用 XPath 语法,这才是正解。以下代码测试通过。            XmlDocument xmldoc = new XmlDocument();
                xmldoc.LoadXml(@"
    <Persons> 
    <Person> 
        <ID>12345678</ID> 
        <Name>小王</Name> 
        <Department>技术中心</Department> 
        <Position>职员</Position> 
        <Password>12345678</Password> 
        <Group>项目</Group> 
        <Action>设计</Action> 
      </Person> 
    </Persons> 
    ");
                string strId = "12345678";
                XmlNode xmlPerson = xmldoc.SelectSingleNode("//Person[ID=" + strId + "]/Name");
                xmlPerson.InnerText = "小张";