1

I'm trying to make a C# program that takes one XML file and turns it into an HTML file, the most obvious way to do such would be with an HtmlTextWriter object, yet I questing needing 6 lines of code to write one tag, an attribute, a line of content, and a closing tag. Is there a cleaner / more efficient way to do this?

The program is using an XML file (format defined by XML Schema) to customize and populate an HTML template with data. An example is shown below:

static string aFileName;
static XmlDocument aParser;
static HtmlTextWriter HTMLIOutput;
static StringWriter HTMLIBuffer;
static StreamWriter HTMLOutIFile;
static HtmlTextWriter HTMLEOutput;
static StringWriter HTMLEBuffer;
static StreamWriter HTMLOutEFile;

HTMLIBuffer = new StringWriter();
HTMLIOutput = new HtmlTextWriter(HTMLIBuffer);
XmlElement feed = aParser.DocumentElement;

HTMLIOutput.WriteBeginTag("em");
HTMLIOutput.WriteAttribute("class", "updated");
HTMLIOutput.Write(HtmlTextWriter.TagRightChar);
HTMLIOutput.Write("Last updated: " + 
feed.SelectSingleNode("updated").InnerText.Trim());
HTMLIOutput.WriteEndTag("em");
HTMLIOutput.WriteLine();
HTMLIOutput.WriteLine("<br>");

To write something such as <em class="updated">Last updated: 07/16/2018</em><br />, do I really need to have so many different lines just constructing parts of a tag?

Note: Yes, I could write the contents to the file directly, but if possible I would prefer a more intelligent way so there's less human error involved.

Teknikal_Domain
  • 318
  • 1
  • 11
  • Could you please describe what you're trying to do, i.e. what is the purpose of your program? Without any more details is hard to tell you what would be the best solution. Have you considered using the Razor engine? See https://github.com/Antaris/RazorEngine – Rui Jarimba Jul 16 '18 at 07:19
  • 1
    You should think about Extensible Stylesheet Language Transformation (XSLT). If you do not like this try HtmlDocument. – Rene Niediek Jul 16 '18 at 07:21
  • At its core level, I'm using an XML Schema defined XML file to customize a built-in HTML template with user data. I'll add a few code examples. And no, at this point I'm only using base C# abilities, though if something else is needed I'll use it. – Teknikal_Domain Jul 16 '18 at 07:22
  • I'd deserialize the XML string into C# objects and then use a library such as the Razor Engine (which I mentioned in my previous comment) to generate the HTML. – Rui Jarimba Jul 16 '18 at 07:25

3 Answers3

1

you can always use 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);

or System.Xml.Linq:

    var html = new XElement("html",
    new XElement("head",
        new XElement("title", "My Page")
    ),
    new XElement("body",
        "this is some text"
    )
);
Barr J
  • 10,636
  • 1
  • 28
  • 46
  • 1
    I believe LINQ is the best choice before adding external libraries, I'll try that. Thanks for suggesting something I completely missed. – Teknikal_Domain Jul 16 '18 at 07:39
1

Is using something like Razor not applicable here? Because if you're doing a lot of html generation using a view engine can make it a lot easier. It was also built to be used outside of ASP.NET.

However sometimes that's not what you need. Have you considered using the TagBuilder class which is part of .net (mvc)? There is also the HtmlWriter in System.Web.UI (for web forms). I would recommend one of these if you are making Controls or Html Helpers.

Hossein
  • 3,083
  • 3
  • 16
  • 33
1

This is my suggestion:

  1. Deserialize the XML into C# objects
  2. Use a template engine such as RazorEngine to generate the HTML

I used RazorEngine in the past to generate email templates (in HTML format). They use a similar syntax to ASP.NET MVC views (.cshtml) and you can even make intellisense works with the templates! Also, templates are much easier to create and maintain, compared to XSLT or TagBuilder.

Consider the following model:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

You can create a string with the HTML template, or use a file. I recommend using a file with a .cshtml extension, so you can have syntax highlighting and intellisense, as already mentioned:

Razor template with intellisense

Template text is the following:

@using RazorEngine.Templating
@using RazorDemo1
@inherits TemplateBase<Person>

<div>
    Hello <strong>@Model.FirstName @Model.LastName</strong>
</div>

Loading the template and generating the HTML:

using System;
using System.IO;

using RazorEngine;
using RazorEngine.Templating;

namespace RazorDemo1
{
    class Program
    {
        static void Main(string[] args)
        {
            string template = File.ReadAllText("./Templates/Person.cshtml");

            var person = new Person
            {
                FirstName = "Rui",
                LastName = "Jarimba"
            };

            string html = Engine.Razor.RunCompile(template, "templateKey", typeof(Person), person);

            Console.WriteLine(html);
        }
    }
}

Output:

<div>
    Hello <strong>Rui Jarimba</strong>
</div>
Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
Rui Jarimba
  • 11,166
  • 11
  • 56
  • 86