【问题标题】:Search contain in xml if found replace whole node如果找到,则在 xml 中搜索包含替换整个节点
【发布时间】:2012-11-01 06:54:12
【问题描述】:

我的 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.
}

谢谢。

【问题讨论】:

  • 如果节点包含 sam,你会用什么替换它,是 sam,sam2,pam
  • 不,我想替换整个节点 bcz width="4,5,91" 不同 :(
  • @freebird &lt;placeholder name="headers" width="30" class="header"&gt;sam,pam&lt;/placeholder&gt; 替换为&lt;placeholder name="headers" width="4,5,91"&gt;sam,sam2,pam&lt;/placeholder&gt;。有什么想法吗?在c# 中可以吗?
  • 让我算出它是可能的。你能用 Linq 吗
  • 我无法使用链接对不起我的项目需求:(

标签: c# asp.net xml


【解决方案1】:
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");

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-22
      • 2021-11-09
      • 2021-01-18
      • 2021-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多