Write HTML to string

前端 未结 18 1411
一生所求
一生所求 2020-12-13 00:04

I have code like this. Is there a way to make it easier to write and maintain? Using C# .NET 3.5.

string header(string title)
{
    StringWriter s = new Stri         


        
相关标签:
18条回答
  • 2020-12-13 00:37

    HSharp is a library used to analyse markup language like HTML easily and fastly. Install: PM> Install-Package Obisoft.HSharp

            var Document = new HDoc(DocumentOptions.BasicHTML);
            Document["html"]["body"].AddChild("div");
            Document["html"]["body"]["div"].AddChild("a", new HProp("href", "/#"));
            Document["html"]["body"]["div"].AddChild("table");
            Document["html"]["body"]["div"]["table"].AddChildren(
             new HTag("tr"),
             new HTag("tr", "SomeText"),
             new HTag("tr", new HTag("td")));
            var Result = Document.GenerateHTML();
            Console.WriteLine(Result);
    

    and output:

    <html>
    <head>
    <meta charset="utf-8"></meta><title>
    Example </title>
    </head>
    <body>
    <div>
    <a href="/#"></a><table>
    <tr></tr><tr>
    SomeText </tr>
    <tr>
    <td></td></tr>
    </table>
    </div>
    </body>
    </html>
    
    0 讨论(0)
  • 2020-12-13 00:40

    You're probably better off using an HtmlTextWriter or an XMLWriter than a plain StringWriter. They will take care of escaping for you, as well as making sure the document is well-formed.

    This page shows the basics of using the HtmlTextWriter class, the gist of which being:

    StringWriter stringWriter = new StringWriter();
    
    using (HtmlTextWriter writer = new HtmlTextWriter(stringWriter))
    {
        writer.AddAttribute(HtmlTextWriterAttribute.Class, classValue);
        writer.RenderBeginTag(HtmlTextWriterTag.Div); // Begin #1
    
        writer.AddAttribute(HtmlTextWriterAttribute.Href, urlValue);
        writer.RenderBeginTag(HtmlTextWriterTag.A); // Begin #2
    
        writer.AddAttribute(HtmlTextWriterAttribute.Src, imageValue);
        writer.AddAttribute(HtmlTextWriterAttribute.Width, "60");
        writer.AddAttribute(HtmlTextWriterAttribute.Height, "60");
        writer.AddAttribute(HtmlTextWriterAttribute.Alt, "");
    
        writer.RenderBeginTag(HtmlTextWriterTag.Img); // Begin #3
        writer.RenderEndTag(); // End #3
    
        writer.Write(word);
    
        writer.RenderEndTag(); // End #2
        writer.RenderEndTag(); // End #1
    }
    // Return the result.
    return stringWriter.ToString();
    
    0 讨论(0)
  • 2020-12-13 00:40

    Use an XDocument to create the DOM, then write it out using an XmlWriter. This will give you a wonderfully concise and readable notation as well as nicely formatted output.

    Take this sample program:

    using System.Xml;
    using System.Xml.Linq;
    
    class Program {
        static void Main() {
            var xDocument = new XDocument(
                new XDocumentType("html", null, null, null),
                new XElement("html",
                    new XElement("head"),
                    new XElement("body",
                        new XElement("p",
                            "This paragraph contains ", new XElement("b", "bold"), " text."
                        ),
                        new XElement("p",
                            "This paragraph has just plain text."
                        )
                    )
                )
            );
    
            var settings = new XmlWriterSettings {
                OmitXmlDeclaration = true, Indent = true, IndentChars = "\t"
            };
            using (var writer = XmlWriter.Create(@"C:\Users\wolf\Desktop\test.html", settings)) {
                xDocument.WriteTo(writer);
            }
        }
    }
    

    This generates the following output:

    <!DOCTYPE html >
    <html>
        <head />
        <body>
            <p>This paragraph contains <b>bold</b> text.</p>
            <p>This paragraph has just plain text.</p>
        </body>
    </html>
    
    0 讨论(0)
  • 2020-12-13 00:40

    You can use T4 Templates for generating Html (or any) from your code. see this: http://msdn.microsoft.com/en-us/library/ee844259.aspx

    0 讨论(0)
  • 2020-12-13 00:41

    You could use System.Xml.Linq objects. They were totally redesigned from the old System.Xml days which made constructing XML from scratch really annoying.

    Other than the doctype I guess, you could easily do something like:

    var html = new XElement("html",
        new XElement("head",
            new XElement("title", "My Page")
        ),
        new XElement("body",
            "this is some text"
        )
    );
    
    0 讨论(0)
  • 2020-12-13 00:43

    This is not a generic solution, however, if your pupose is to have or maintain email templates then System.Web has a built-in class called MailDefinition. This class is used by the ASP.NET membership controls to create HTML emails.

    Does the same kind of 'string replace' things as mentioned above, but packs it all into a MailMessage for you.

    Here is an example from MSDN:

    ListDictionary replacements = new ListDictionary();
    replacements.Add("<%To%>",sourceTo.Text);
    replacements.Add("<%From%>", md.From);
    System.Net.Mail.MailMessage fileMsg;
    fileMsg = md.CreateMailMessage(toAddresses, replacements, emailTemplate, this); 
    return fileMsg;
    
    0 讨论(0)
提交回复
热议问题