为所有 children 添加 class

add class for all children

我有一些 html,..例如:

<div id='mainDiv'>
   <ul>
      <li>1</li>
      <li>2</li>
      <li>3</li>
   </ul>
   <div><span>text</span></div>
   <div><span>another text</span></div>
   <p>lalala</p>
</div>

我如何从 mainDiv 中获取所有子项并在每个 children

中添加一些 data-attr
HtmlNode mainDiv = document.DocumentNode.SelectSingleNode("//div[@id='mainDiv']");

替代方案只是遍历子项

class Program
{
    static void Main(string[] args)
    {
        HtmlDocument document = new HtmlDocument();
        document.Load("Demo.html");

        HtmlNode mainDiv = document.DocumentNode.SelectSingleNode("//div[@id='mainDiv']");

        foreach (var child in mainDiv.ChildNodes)
        {
            if (child.Attributes.Any(att=> att.Name == "class"))
            {
                child.Attributes["class"].Value = "data-attr";
            }
            else
            {
                child.Attributes.Add("class", "data-attr");
            }
        }

        document.Save("Demo.html");
    }
}

或所有后代:

class Program
{
    static void Main(string[] args)
    {
        HtmlDocument document = new HtmlDocument();
        document.Load("Demo.html");

        HtmlNode mainDiv = document.DocumentNode.SelectSingleNode("//div[@id='mainDiv']");

        foreach (var child in mainDiv.Descendants())
        {
            if (child.Attributes.Any(att=> att.Name == "class"))
            {
                child.Attributes["class"].Value = "data-attr";
            }
            else
            {
                child.Attributes.Add("class", "data-attr");
            }
        }

        document.Save("Demo.html");
    }
}