Pete Pete - 28 days ago 6x
C# Question

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

Is it possible using the C# HTML Agility Pack to insert a variable into the selected node?

I have created my HTML form, loaded it, and selected the input node that I want, and now I would like to inject in the value field a SAML Response

Here is a bit of the code that I have, first the HTML document:

<html xmlns="">
<head id="Head1" runat="server">
<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=""/>

and here is the function which loads the HTML document and selects the node I want:

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

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


Ok so I have achieved injecting the SAML Response packet into the "value" field of the html input tag with this:

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

Now I just need to be able to add that injected tag back into the original HTML document


ok I have solved this using the following:

HtmlAgilityPack.HtmlDocument HtmlDoc = new HtmlAgilityPack.HtmlDocument();
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);

Then in order to check the contents of the new HTML file I output it using this:

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