DaveDev
DaveDev

Reputation: 42185

How to programmatically load a HTML document in order to add to the document's <head>?

We are supplied with HTML 'wrapper' files from the client, which we need to insert out content into, and then render the HTML.

Before we render the HTML with our content inserted, I need to add a few tags to the <head> section of the client's wrapper, such as references to our script files, css and some meta tags.

So what I'm doing is

string html = File.ReadAllText(wrapperLocation, Encoding.GetEncoding("iso-8859-1"));

and now I have the complete HTML. I then search for a pre-defined content well in that string and insert our content into that, and render it.

How can I create an instance of a HTML document and modify the <head> section as required?

edit: I don't want to reference System.Windows.Forms so WebBrowser is not an option.

Upvotes: 1

Views: 1563

Answers (5)

Matt Urtnowski
Matt Urtnowski

Reputation: 2566

You can use https://github.com/jamietre/CsQuery to edit an html dom.

var dom = CQ.Create(html);
var dom = CQ.CreateFromUrl("http://www.jquery.com");

dom.Select("div > span")
.Eq(1)
.Text("Change the text content of the 2nd span child of each div");

Just select the head and add to it.

Upvotes: 1

Peter
Peter

Reputation: 864

Are you using MasterPages? This seems like the most obvious use of them.

The MasterPage has <asp:ContentPlaceHolder>'s for all the points where you want the content to go.

In our app we have a base controller that overrides all the View() overloads so that it reads in the name of the MasterPage from the web.config. That way customising the app is as simple as a new MasterPage and from a Controllers point of view there is no code change since our base class handles the MasterPage/web.config stuff.

Upvotes: 0

DaveDev
DaveDev

Reputation: 42185

I couldn't get an automated solution to this, so it came down to a hack:

public virtual void PopulateCssTag(string tags)
{
    // tags is a pre-compsed string containing all the tags I need.
    this.Wrapper = this.Wrapper.Replace("</head>", tags + "</head>");
}

Upvotes: -1

user243966
user243966

Reputation:

I haven't tried this library myself, but this would probably fit the bill: http://htmlagilitypack.codeplex.com/

Upvotes: 1

Mau
Mau

Reputation: 14478

I use the WebBrowser control as host, and navigate/alter the document through its Document property.

Nice documentation and samples at the link above.

Upvotes: 0

Related Questions