// Copyright © 2015 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; namespace CefSharp { /// /// Represents a node in the browser's DOM. /// public class DomNode : IDomNode { private readonly IDictionary attributes; /// /// Constructor. /// /// Name of the tag. /// The attributes. public DomNode(string tagName, IDictionary attributes) { TagName = tagName; this.attributes = attributes; } /// /// Returns a string that represents the current object. /// /// /// A string that represents the current object. /// public override string ToString() { var sb = new StringBuilder(); if (attributes != null) { foreach (var pair in attributes) { sb.AppendFormat("{0}{1}:'{2}'", 0 < sb.Length ? ", " : String.Empty, pair.Key, pair.Value); } } if (!String.IsNullOrWhiteSpace(TagName)) { sb.Insert(0, String.Format("{0} ", TagName)); } if (sb.Length < 1) { return base.ToString(); } return sb.ToString(); } /// /// Get the value of an attribute. /// /// The name of the attribute value to get. /// /// The attribute value if the name exists in the DomNode's attributes. Null if the name does not exist. /// public string this[string name] { get { if (attributes == null || attributes.Count < 1 || !attributes.ContainsKey(name)) { return null; } return attributes[name]; } } /// /// The name of the HTML element. /// /// /// The name of the tag. /// public string TagName { get; private set; } /// /// Get a read only list of the attribute names. /// /// /// A list of names of the attributes. /// public ReadOnlyCollection AttributeNames { get { if (attributes == null) { return new ReadOnlyCollection(new List()); } return Array.AsReadOnly(attributes.Keys.ToArray()); } } /// /// Determine if the DomNode has the requested attribute. /// /// The name of the attribute value. /// /// True if the attribute exists in the DomNode, false if it does not. /// public bool HasAttribute(string attributeName) { if (attributes == null) { return false; } return attributes.ContainsKey(attributeName); } /// /// Gets the enumerator. /// /// /// The enumerator. /// public IEnumerator> GetEnumerator() { if (attributes == null) { return new Dictionary().GetEnumerator(); } return attributes.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } } }