// /** // * 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 children = new List(); Dictionary attributes = new Dictionary(); public IEnumerable> Attributes => attributes; public Element(string elementName) { Name = elementName; } public Element(string elementName,IEnumerable> attributes) :this(elementName) { foreach (KeyValuePair 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 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 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("",Name); } } public override string ToString() { StringWriter stringWriter = new StringWriter(); Render(stringWriter); return stringWriter.ToString(); } static HashSet voidElementNames = new HashSet(){ "!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); } }