本文介绍了TagBuilder查找特定的内部元素并添加新属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个TagBuilder,其中包含外部元素和内部元素。如何遍历输入级别行,并将以下内容添加为新属性?

I have a TagBuilder which contains Outer and Inner Elements. How do I traverse to the Input level line , and Add the following as an New attribute?

placeholder = Search

<div class="form-group">
    <div class="cont label-outside">
        <label>Name</label>
        <div class="group">
            <input type="text" required="required" class="focusedOut">
            <span class="highlight"></span>
            <span class="bar"></span>
            <span class="close-button" onclick="clear()"></span>
        </div>
    </div>
</div>

如果不存在Tagbuilder / Taghelper方法,是否应使用C#HTML Agility软件包来编辑标签树? ;如果是,如何将Tagbuilder /或Taghelper输出转换为Agility Package HTMLDocument?

If no Tagbuilder/Taghelper method exists, should C# HTML Agility package be utilized to edit tag tree? https://html-agility-pack.net/traversing ; If yes, how to convert Tagbuilder/ or Taghelper Output into Agility Package HTMLDocument?

*这与问题,因为这要求编辑现有属性。这里的问题是关于添加新属性。参见以下文章:

*This is different from question Add CSS Class to All Tags in TagBuilder, Edit Existing Attribute as this asks to Edit existing attribute. Question here is about Adding New Attribute. See article below :

推荐答案

对于您的任务,您可以使用。

For your task you can use HtmlAgilityPack.

使用 HtmlAgilityPack ,您可以使用 XPath查询选择必要的节点并将标签添加到该节点。

Using HtmlAgilityPack you can use XPath Query to select necessary nodes and add tag to this node.

要选择节点,可以使用方法:

To select nodes you can use SelectNodes method:

var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(html);
var nodes = htmlDoc.DocumentNode.SelectNodes("//input[contains(@class, 'focusedOut')]");

要添加属性,您可以使用:

To add attribute you can use Attributes Collection:

node.Attributes.Add("placeholder","Search");

这篇关于TagBuilder查找特定的内部元素并添加新属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 15:21