views:

47

answers:

3

Guys, Assuming I have the following ASP.NET HTML Code:

<html>
    <head><title>Test Page</title></head>
    <body id="bodyID">
        <asp:Label runat="server" id="lbl1" text="First Name:" />
        <asp:TextBox runat="server" id="txt1" /><br />
        <asp:Label runat="server" id="lbl2" text="Last Name:" />
        <asp:TextBox runat="server" id="txt2"></asp:TextBox>
    </body>
</html>

I am trying to write a linq query that will retrieve all the ID's from any asp tag. Also, the query needs to group everything together alphabetically. So for the example above, the linq query should return "lbl1", followed by "lbl2", followed by "txt1", and finally "txt2". Notice it did not grab the "bodyID" because it was not part of an ASP.NET tag. Is there an easy way to do this? I am using C#, by the way.

A: 

The easiest way to do this would be do write a regular expression to extract all the id's and then sort the list. since each element starts with <asp:, it should be pretty easy to do. If i had a bit more time i'd work out the regex.

Alex
A: 

You might be able to parse it.

Create temp file, add a header for whatever type of parser you want to use.

Add the html/asp code to the temp file and close it.

Parse the file using your favorite parsing library.

Cycle through the ASP nodes, adding them to a list.

Sort the list.

You could also do it with Regular Expressions.

Guy
+1  A: 

If you'd like to use Linq To XML, you'd have to work around the <asp:> tags and that they don't load cleanly into XML.

This code will get you what you're looking for, assuming:

  • you can load your ASPX markup into a string
  • the ASPX markup is valid XML.

The replacement of the asp: with asp- may cause trouble if you have any valid asp: content that isn't in a tag. This could be cleaned up to make it suit your needs.

  public static void Main(string[] args)
    {
        string aspxCode = @"<html><head><title>Test Page</title></head>
                            <body id=""bodyID"">        
        <asp:Label runat=""server"" id=""lbl1"" text=""First Name:"" />
        <asp:TextBox runat=""server"" id=""txt1"" /><br />
        <asp:Label runat=""server"" id=""lbl2"" text=""Last Name:"" />
        <asp:TextBox runat=""server"" id=""txt2""></asp:TextBox>
    </body>
</html>";

        XElement xDoc = XElement.Parse(aspxCode.Replace("asp:", "asp-"));

        var allMatchingASPtags = xDoc.Descendants()
               .Where(d => d.Name.LocalName.StartsWith("asp-"))
               .Select(c => c.Attribute("id").Value);

        foreach (var t in allMatchingASPtags)
        {
            Console.WriteLine(t);
        }

        Console.ReadLine();
p.campbell
I stumbled into Linq to XML the other day and it has been a huge help!
Dillie-O
Good solution, but I would be wary of the ASP page declaratives, e.g. <% ... %> and <%: %> etc...
Matthew Abbott