using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using System.Xml; using System.Security; namespace FastReport.Messaging.Xmpp { /// /// Represents a static class to simplify the work with XmlElement instance. /// internal static class Xml { #region Public Methods /// /// Creates a new XmlElement instance. /// /// The name of the element. /// The namespace of the element. /// A new instance of the class. public static XmlElement CreateElement(string name, string nspace) { return new XmlDocument().CreateElement(name, nspace); } /// /// Adds the specified child to the end of child nodes of element. /// /// The element for add the child to. /// The child node to add. /// A XmlElement instance. public static XmlElement AddChild(XmlElement element, XmlElement child) { XmlNode node = element.OwnerDocument.ImportNode(child, true); element.AppendChild(node); return element; } /// /// Adds the attribute to XmlElement with spefied name and value. /// /// The element for add the attribute to. /// The name of attribute. /// The value of attribute. /// A XmlElement instance. public static XmlElement AddAttribute(XmlElement element, string name, string value) { element.SetAttribute(name, value); return element; } /// /// Adds the specified text to the end of child nodes of element. /// /// The element for add the text to. /// The text for add. /// A XmlElement instance. public static XmlElement AddText(XmlElement element, string text) { element.AppendChild(element.OwnerDocument.CreateTextNode(text)); return element; } /// /// Converts the XmlElement instance to a string. /// /// The element to convert to. /// True if needed to include XML declaration. /// True if needed to leave the tag of an empty element open. /// The XmlElement instance as string. public static string ToXmlString(XmlElement element, bool includeDeclaration, bool leaveOpen) { StringBuilder sb = new StringBuilder("<" + element.Name); if (!String.IsNullOrEmpty(element.NamespaceURI)) { sb.Append(" xmlns='" + element.NamespaceURI + "'"); } foreach (XmlAttribute attribute in element.Attributes) { if (attribute.Name != "xmlns" && attribute.Value != null) { sb.Append(" " + attribute.Name + "='" + SecurityElement.Escape(attribute.Value.ToString()) + "'"); } } if (element.IsEmpty) { sb.Append("/>"); } else { sb.Append(">"); foreach (XmlNode child in element.ChildNodes) { if (child is XmlElement) { sb.Append(Xml.ToXmlString(child as XmlElement, false, false)); } else if (child is XmlText) { sb.Append((child as XmlText).InnerText); } } sb.Append(""); } string xml = ""; if (includeDeclaration) { //xml = ""; xml = ""; } xml += sb.ToString(); if (leaveOpen) { xml = Regex.Replace(xml, "/>$", ">"); } return xml; } #endregion // Public Methods } }