1

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

谢谢。

4

2 回答 2

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");
于 2012-11-01T07:45:08.143 回答
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);
    }
}
于 2012-11-01T07:20:53.723 回答