Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 搜索包含在xml中(如果找到)替换整个节点_C#_Asp.net_Xml - Fatal编程技术网

C# 搜索包含在xml中(如果找到)替换整个节点

C# 搜索包含在xml中(如果找到)替换整个节点,c#,asp.net,xml,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="Cont

我的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>
而不是:

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

谢谢。

尝试使用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);
    }
}

如果节点包含sam,您将用什么替换它,是sam,sam2,pamNop我要替换整个节点bcz
width=“4,5,91”
不同:(@freebird
sam,pam
repalce with
sam,sam2,pam
。有什么想法吗?在c#中可能吗?让我来计算一下它是可能的。你能用林琦吗?我无法使用链接抱歉,这是我的项目需求:(
XmlDocument doc = new XmlDocument();
string sFileName = @"FileNameWithPath";
doc.Load(sFileName );
foreach (XmlNode ....... )
{
    //Need help hear how to loop and replace.
}
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);
    }
}
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");