101 lines
3.2 KiB
C#
101 lines
3.2 KiB
C#
// /**
|
|
// * File: Element.cs
|
|
// * Author: haraldwolff
|
|
// *
|
|
// * This file and it's content is copyrighted by the Author and / or copyright holder.
|
|
// * Any use wihtout proper permission is illegal and may lead to legal actions.
|
|
// *
|
|
// *
|
|
// **/
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
namespace ln.templates.html
|
|
{
|
|
public class Element
|
|
{
|
|
public string Name { get; }
|
|
public Element Parent { get; private set; }
|
|
|
|
public bool IsVoid => IsVoidElement(Name);
|
|
|
|
List<Element> children = new List<Element>();
|
|
Dictionary<string, string> attributes = new Dictionary<string, string>();
|
|
public IEnumerable<KeyValuePair<string, string>> Attributes => attributes;
|
|
|
|
public Element(string elementName)
|
|
{
|
|
Name = elementName;
|
|
}
|
|
public Element(string elementName,IEnumerable<KeyValuePair<string,string>> attributes)
|
|
:this(elementName)
|
|
{
|
|
foreach (KeyValuePair<string, string> keyValuePair in attributes)
|
|
this.attributes[keyValuePair.Key] = keyValuePair.Value;
|
|
}
|
|
|
|
public virtual bool HasAttribute(string attributeName) => attributes.ContainsKey(attributeName);
|
|
public virtual string GetAttribute(string attributeName) => attributes[attributeName];
|
|
public virtual void SetAttribute(string attributeName, string attributeValue) => attributes[attributeName] = attributeValue;
|
|
|
|
public IEnumerable<Element> Children => children;
|
|
public void AppendChild(Element element)
|
|
{
|
|
if (element.Parent != null)
|
|
element.Parent.RemoveChild(element);
|
|
|
|
if (IsVoid)
|
|
{
|
|
Parent.AppendChild(element);
|
|
}
|
|
else
|
|
{
|
|
children.Add(element);
|
|
element.Parent = this;
|
|
}
|
|
}
|
|
public void RemoveChild(Element element)
|
|
{
|
|
if (element.Parent != this)
|
|
throw new KeyNotFoundException();
|
|
|
|
children.Remove(element);
|
|
element.Parent = null;
|
|
}
|
|
|
|
public virtual void Render(TextWriter writer)
|
|
{
|
|
writer.Write("<{0}", Name);
|
|
foreach (KeyValuePair<String, String> attributePair in attributes)
|
|
writer.Write(" {0}=\"{1}\"", attributePair.Key, attributePair.Value);
|
|
writer.Write(">");
|
|
|
|
if (!IsVoid)
|
|
{
|
|
foreach (Element element in children)
|
|
element.Render(writer);
|
|
|
|
writer.Write("</{0}>",Name);
|
|
}
|
|
}
|
|
|
|
public override string ToString()
|
|
{
|
|
StringWriter stringWriter = new StringWriter();
|
|
Render(stringWriter);
|
|
return stringWriter.ToString();
|
|
}
|
|
|
|
|
|
|
|
static HashSet<string> voidElementNames = new HashSet<string>(){
|
|
"!doctype",
|
|
"area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr"
|
|
};
|
|
public static string[] VoidElementNames => voidElementNames.ToArray();
|
|
public bool IsVoidElement(string elementName) => voidElementNames.Contains(elementName);
|
|
|
|
}
|
|
}
|