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

c# html html-agility-pack saml

Question

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="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>

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();
    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
}

EDIT:

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";
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 + "'/>";

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

Accepted Answer

ok I have solved this using the following:

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);
}

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);



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why