搜索包含xml如果找到替换整个节点

时间:2012-11-01 06:54:13

标签: c# asp.net xml

我的xml文件:

<?xml version="1.0" encoding="utf-8"?>
<layout name="layout">
  <section name="Header">
    <placeholder name="headers" width="30" class="header">sam,pam</placeholder>
  </section>
  <section name="Content">
    <placeholder name="RightA" width="55">location</placeholder>
  </section>
</layout>

我想替换整个节点,如果它包含sam。意味着节点是否包含sam我想重写节点:

<placeholder name="headers" width="4,5,91">sam,sam2,pam</placeholder>

而不是:

<placeholder name="headers" width="30" class="header">sam,pam</placeholder>

在c#中:

XmlDocument doc = new XmlDocument();
string sFileName = @"FileNameWithPath";
doc.Load(sFileName );
foreach (XmlNode ....... )
{
    //Need help hear how to loop and replace.
}

感谢。

2 个答案:

答案 0 :(得分:0)

尝试使用XDocument更好地控制查找和替换。

XDocument myDocument = XDocument.Load("path to my file");
foreach (XElement node in myDocument.Root.Descendants("placeholder"))
{
    if (node.Value.Contains("same"))
    {
        XElement newNode = new XElement("placeholder");
        newNode.Add(new XAttribute("header", node.Attribute("header").Value); // if you want to copy the current value
        newNode.Add(new XAttribute("width", "some new value"));
        node.ReplaceWith(newNode);
    }
}

答案 1 :(得分:0)

XmlDocument xmlDoc = new XmlDocument();
 xmlDoc.Load("Path");
 XmlNodeList nodeList = xmlDoc.SelectNodes("section") ;

 foreach (XmlNode node in nodeList)
   {
      XmlNode childNode = node.SelectSingleNode("placeholder");
        if (childNode.Value.Contains("sam"))
          {
              childNode.Value = "sam,pam,sam2";
              childNode.Attributes["width"].Value = "4,5,91";

           }
   }

 xmlDoc.Save("Path");