2

I want to be able to add attributes to a string of html without having to build a parser to handle the html. In one specific case, I want to be able to extract the id of the html or insert an id to the html server side.

Say I have:

string stringofhtml = "<img src=\"someimage.png\" alt=\"the image\" />";

I would like to be able to do something like:

HtmlGenericControl htmlcontrol = new HtmlGenericControl(stringofhtml);
htmlcontrol.Attributes["id'] = "newid";

OR

int theid = htmlcontrol.Attributes["id"];

This is just a way that I can access/add attributes of the html strings that I have.

2 Answers 2

6

You can do this:

HtmlGenericControl ctrl = new HtmlGenericControl();
ctrl.InnerHtml = "<img src=\"someimage.png\" alt=\"the image\" />"; 

You could always use a LiteralControl too, instead of an HtmlGenericControl:

LiteralControl lit = new LiteralControl(stringOfHtml);
Sign up to request clarification or add additional context in comments.

6 Comments

James, this way <img> tag will be wrapped up by <span> tag (default HtmlGenericControl's tag with no param passed)
But then ctrl.Attributes["id"] = newid would be setting the id of the span, right?
Igor, thanks for pointing that out. I'm basically looking for a way to build an html genetic control that will reflect the html string exactly. So even if it is a div with html inside it I'd like that to still be available. Maybe I have to build a parser anyways?
@Igor that solution is going in the opposite direction of what I am hoping to do. I will try to explain more in my question.
Sorry for not being very clear, I just think building kind of parser is a way to go. You cannot do it with HtmlGenericControl because it works with tags only
|
3

I do not think there is a control available which will provide you with the functionality you are looking for.

Below I have made use of the HtmlAgility pack to parse/query the HTML and created a new control subclassing the Literal control.

This control accepts an HTML string, checks to ensure it contains at least a single element and provides access to get/set that elements attributes.

Example usage

string image = "<img src=\"someimage.png\" alt=\"the image\" />";

HtmlControlFromString htmlControlFromString = new HtmlControlFromString(image);

htmlControlFromString.Attributes["id"] = "image2";

string id = htmlControlFromString.Attributes["id"];

Control

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using HtmlAgilityPack;

public class HtmlControlFromString : Literal
{
    private HtmlDocument _document = new HtmlDocument();
    private HtmlNode _htmlElement;

    public AttributesCollection Attributes { get; set; }

    public HtmlControlFromString(string html)
    {
        _document.LoadHtml(html);
        if (_document.DocumentNode.ChildNodes.Count > 0)
        {
            _htmlElement = _document.DocumentNode.ChildNodes[0];

            Attributes = new AttributesCollection(_htmlElement);
            Attributes.AttributeChanged += new EventHandler(Attributes_AttributeChanged);

            SetHtml();
        }
        else
        {
            throw new InvalidOperationException("Argument does not contain a valid html element.");
        }
    }

    void Attributes_AttributeChanged(object sender, EventArgs e)
    {
        SetHtml();
    }

    void SetHtml()
    {
        Text = _htmlElement.OuterHtml;
    }
}

public class AttributesCollection
{
    public event EventHandler AttributeChanged;

    private HtmlNode _htmlElement;

    public string this[string attribute]
    {
        get
        {
            HtmlAttribute htmlAttribute = _htmlElement.Attributes[attribute];
            return htmlAttribute == null ? null : htmlAttribute.Value;
        }
        set
        {
            HtmlAttribute htmlAttribute = _htmlElement.Attributes[attribute];
            if (htmlAttribute == null)
            {
                htmlAttribute = _htmlElement.OwnerDocument.CreateAttribute(attribute);
                htmlAttribute.Value = value;
                _htmlElement.Attributes.Add(htmlAttribute);
            }
            else
            {
                htmlAttribute.Value = value;
            }

            EventHandler attributeChangedHandler = AttributeChanged;
            if (attributeChangedHandler != null)
                attributeChangedHandler(this, new EventArgs());
        }
    }

    public AttributesCollection(HtmlNode htmlElement)
    {
        _htmlElement = htmlElement;
    }
}

Hope this helps.

1 Comment

Thank you for the detailed example and usage. That's exactly what I am looking for. I ended up writing my own parsers hours ago, but I am sure this one is much more robust. So I will go with this solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.