使用 Html Agility Pack C# 将变量注入 html 输入标签值

Inject variable into html input tag value using Html Agility Pack C#

是否可以使用 C# HTML Agility Pack 将变量插入所选节点?

我已经创建了我的 HTML 表单,加载它,并选择了我想要的输入节点,现在我想在值字段中注入一个 SAML 响应

这是我的一些代码,首先是 HTML 文档:

<html xmlns="http://www.w3.org/1999/xhtml">
<head  id="Head1" runat="server">
    <title></title>
</head>
<body runat="server" id="bodySSO">
    <form id="frmSSO" runat="server" enableviewstate="False">
        <div style="display:none" >
            <input id="SAMLResponse" name="SAMLResponse" type="text" runat="server" enableviewstate="False" value=""/>
            <input id="Query" name="Query" type="text" runat="server" enableviewstate="False" value=""/>
        </div>
    </form>
</body>
</html>

这是加载 HTML 文档并选择我想要的节点的函数:

public static string GetHTMLForm(SamlAssertion samlAssertion)
{
    HtmlAgilityPack.HtmlDocument HTMLSamlDocument = new HtmlAgilityPack.HtmlDocument();
    HTMLSamlDocument.Load(@"C:\HTMLSamlForm.html");
    HtmlNode node = HTMLSamlDocument.DocumentNode.SelectNodes("//input[@id='SAMLResponse']").First();

    //Code that will allow me to inject into the value field my SAML Response
}

编辑:

好的,我已经实现了将 SAML 响应数据包注入到 html 输入标签的 "value" 字段中:

HtmlAgilityPack.HtmlDocument HtmlDoc = new HtmlAgilityPack.HtmlDocument();
String SamlInjectedPath = "C:\SamlInjected.txt";
HtmlDoc.Load(@"C:\HTMLSamlForm.txt");
var SAMLResposeNode = HtmlDoc.DocumentNode.SelectSingleNode("//input[@id='SAMLResponse']").ToString();
SAMLResposeNode = "<input id='SAMLResponse' name='SAMLResponse' type='text' runat='server' enableviewstate='False' value='" + samlAssertion + "'/>";

现在我只需要能够将注入的标签添加回原始 HTML 文档

好的,我已经使用以下方法解决了这个问题:

HtmlAgilityPack.HtmlDocument HtmlDoc = new HtmlAgilityPack.HtmlDocument();
HtmlDoc.Load(@"C:\HTMLSamlForm.html");
var SamlNode = HtmlNode.CreateNode("<input id='SAMLResponse' name='SAMLResponse' type='text' runat='server' enableviewstate='False' value='" + samlAssertion + "'/>");
foreach (HtmlNode node in HtmlDoc.DocumentNode.SelectNodes("//input[@id='SAMLResponse']"))
{
    string value = node.Attributes.Contains("value") ? node.Attributes["value"].Value : "&nbsp;";
    node.ParentNode.ReplaceChild(SamlNode, node);
}

然后为了检查新 HTML 文件的内容,我用这个输出它:

System.IO.File.WriteAllText(@"C:\SamlInjected.txt", HtmlDoc.DocumentNode.OuterHtml);