Write HTML to string

前端 未结 18 1476
一生所求
一生所求 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: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:

    
    
        
        
            

    This paragraph contains bold text.

    This paragraph has just plain text.

提交回复
热议问题