context: //
  // System.Xml.XmlDocument
  //
  // Authors:
  //   Daniel Weber (daniel-weber@austin.rr.com)
  //   Kral Ferch <kral_ferch@hotmail.com>
  //   Jason Diamond <jason@injektilo.org>
  //   Miguel de Icaza (miguel@ximian.com)
  //   Duncan Mak (duncan@ximian.com)
  //   Atsushi Enomoto (ginga@kit.hi-ho.ne.jp)
  //
  // (C) 2001 Daniel Weber
  // (C) 2002 Kral Ferch, Jason Diamond, Miguel de Icaza, Duncan Mak,
  //   Atsushi Enomoto
  // Copyright (C) 2005 Novell, Inc (http://www.novell.com)
  //
  // Permission is hereby granted, free of charge, to any person obtaining
  // a copy of this software and associated documentation files (the
  // "Software"), to deal in the Software without restriction, including
  // without limitation the rights to use, copy, modify, merge, publish,
  // distribute, sublicense, and/or sell copies of the Software, and to
  // permit persons to whom the Software is furnished to do so, subject to
  // the following conditions:
  // 
  // The above copyright notice and this permission notice shall be
  // included in all copies or substantial portions of the Software.
  // 
  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  //
  
  using System.Globalization;
  using System.IO;
  using System.Security.Permissions;
  using System.Text;
  using System.Xml.XPath;
  using System.Diagnostics;
  using System.Collections;
  using Mono.Xml;
  #if NET_2_0
  using System.Xml.Schema;
  using Mono.Xml.XPath;
  #endif
  
  namespace System.Xml
  {
  	public class XmlDocument : XmlNode, IHasXmlChildNode
  	{
  		#region Fields
  		static readonly Type [] optimal_create_types = new Type [] {typeof (string), typeof (string), typeof (string)};
  		bool optimal_create_element, optimal_create_attribute;
  
  		XmlNameTable nameTable;
  		string baseURI = String.Empty;
  		XmlImplementation implementation;
  		bool preserveWhitespace = false;
  		XmlResolver resolver;
  		Hashtable idTable = new Hashtable ();
  		XmlNameEntryCache nameCache;
  		XmlLinkedNode lastLinkedChild;
  		XmlAttribute nsNodeXml;
  #if NET_2_0
  		XmlSchemaSet schemas;
  		IXmlSchemaInfo schemaInfo;
  #endif
  
  		// MS.NET rejects undeclared entities _only_ during Load(),
  		// while ReadNode() never rejects such node. So it signs
  		// whether we are on Load() or not (MS.NET uses Loader class,
  		// but we don't have to implement Load() as such)
  		bool loadMode;
  
  		#endregion
  
  		#region Constructors
  
  		public XmlDocument () : this (null, null)
  		{
  		}
  
  		protected internal XmlDocument (XmlImplementation imp) : this (imp, null)
  		{
  		}
  
  		public XmlDocument (XmlNameTable nt) : this (null, nt)
  		{
  		}
  
  		XmlDocument (XmlImplementation impl, XmlNameTable nt) : base (null)
  		{
  			if (impl == null)
  				implementation = new XmlImplementation ();
  			else
  				implementation = impl;
  
  			nameTable = (nt != null) ? nt : implementation.InternalNameTable;
  			nameCache = new XmlNameEntryCache (nameTable);
  			AddDefaultNameTableKeys ();
  			resolver = new XmlUrlResolver ();
  			
  			Type type = GetType ();
  			optimal_create_element = type.GetMethod ("CreateElement", optimal_create_types).DeclaringType == typeof (XmlDocument);
  			optimal_create_attribute = type.GetMethod ("CreateAttribute", optimal_create_types).DeclaringType == typeof (XmlDocument);
  		}
  		#endregion
  
  		#region Events
  
  		public event XmlNodeChangedEventHandler NodeChanged;
  
  		public event XmlNodeChangedEventHandler NodeChanging;
  
  		public event XmlNodeChangedEventHandler NodeInserted;
  
  		public event XmlNodeChangedEventHandler NodeInserting;
  
  		public event XmlNodeChangedEventHandler NodeRemoved;
  
  		public event XmlNodeChangedEventHandler NodeRemoving;
  
  		#endregion
  
  		#region Properties
  
  		internal XmlAttribute NsNodeXml {
  			get {
  				if (nsNodeXml == null) {
  					nsNodeXml = CreateAttribute ("xmlns", "xml", "http://www.w3.org/2000/xmlns/");
  					nsNodeXml.Value = "http://www.w3.org/XML/1998/namespace";
  				}
  				return nsNodeXml;
  			}
  		}
  
  		XmlLinkedNode IHasXmlChildNode.LastLinkedChild {
  			get { return lastLinkedChild; }
  			set { lastLinkedChild = value; }
  		}
  
  		public override string BaseURI {
  			get {
  				return baseURI;
  			}
  		}
  
  		public XmlElement DocumentElement {
  			get {
  				XmlNode node = FirstChild;
  
  				while (node != null) {
  					if (node is XmlElement)
  						break;
  					node = node.NextSibling;
  				}
  
  				return node != null ? node as XmlElement : null;
  			}
  		}
  
  		public virtual XmlDocumentType DocumentType {
  			get {
  				for (XmlNode n = FirstChild; n != null; n = n.NextSibling) {
  					if (n.NodeType == XmlNodeType.DocumentType)
  						return (XmlDocumentType) n;
  					else if (n.NodeType == XmlNodeType.Element) // document element
  						return null;
  				}
  
  				return null;
  			}
  		}
  
  		public XmlImplementation Implementation {
  			get { return implementation; }
  		}
  
  #if NET_4_0
  		public override string InnerText {
  			set { throw new InvalidOperationException (); }
  		}
  #endif
  
  		public override string InnerXml {
  			get {
  				return base.InnerXml;
  			}
  			set {	// reason for overriding
  				this.LoadXml (value);
  			}
  		}
  
  		public override bool IsReadOnly {
  			get { return false; }
  		}
  
  		internal bool IsStandalone {
  			get {
  				return FirstChild != null &&
  					FirstChild.NodeType == XmlNodeType.XmlDeclaration &&
  					((XmlDeclaration) this.FirstChild).Standalone == "yes";
  			}
  		}
  
  		public override string LocalName {
  			get { return "#document"; }
  		}
  
  		public override string Name {
  			get { return "#document"; }
  		}
  
  		internal XmlNameEntryCache NameCache {
  			get { return nameCache; }
  		}
  
  		public XmlNameTable NameTable {
  			get { return nameTable; }
  		}
  
  		public override XmlNodeType NodeType {
  			get { return XmlNodeType.Document; }
  		}
  
  		internal override XPathNodeType XPathNodeType {
  			get {
  				return XPathNodeType.Root;
  			}
  		}
  
  		public override XmlDocument OwnerDocument {
  			get { return null; }
  		}
  
  		public bool PreserveWhitespace {
  			get { return preserveWhitespace; }
  			set { preserveWhitespace = value; }
  		}
  
  		internal XmlResolver Resolver {
  			get { return resolver; }
  		}
  
  		internal override string XmlLang {
  			get { return String.Empty; }
  		}
  
  		public virtual XmlResolver XmlResolver {
  			set { resolver = value; }
  		}
  
  		internal override XmlSpace XmlSpace {
  			get {
  				return XmlSpace.None;
  			}
  		}
  		
  		internal Encoding TextEncoding {
  			get {
  				XmlDeclaration dec = FirstChild as XmlDeclaration;
  			
  				if (dec == null || dec.Encoding == "")
  					return null;
  				
  				return Encoding.GetEncoding (dec.Encoding);
  			}
  		}
  
  #if NET_2_0
  		public override XmlNode ParentNode {
  			get { return null; }
  		}
  
  		public XmlSchemaSet Schemas {
  			get {
  				if (schemas == null)
  					schemas = new XmlSchemaSet ();
  				return schemas;
  			}
  			set { schemas = value; }
  		}
  
  		public override IXmlSchemaInfo SchemaInfo {
  			get { return schemaInfo; }
  			internal set { schemaInfo = value; }
  		}
  #endif
  
  		#endregion
  
  		#region Methods
  		internal void AddIdenticalAttribute (XmlAttribute attr)
  		{
  			idTable [attr.Value] = attr;
  		}
  
  		public override XmlNode CloneNode (bool deep)
  		{
  			XmlDocument doc = implementation != null ? implementation.CreateDocument () : new XmlDocument ();
  			doc.baseURI = baseURI;
  
  			if(deep)
  			{
  				for (XmlNode n = FirstChild; n != null; n = n.NextSibling)
  					doc.AppendChild (doc.ImportNode (n, deep), false);
  			}
  			return doc;
  		}
  
  		public XmlAttribute CreateAttribute (string name)
  		{
  			string prefix;
  			string localName;
  			string namespaceURI = String.Empty;
  
  			ParseName (name, out prefix, out localName);
  
  			if (prefix == "xmlns" || (prefix == "" && localName == "xmlns"))
  				namespaceURI = XmlNamespaceManager.XmlnsXmlns;
  			else if (prefix == "xml")
  				namespaceURI = XmlNamespaceManager.XmlnsXml;
  
  			return CreateAttribute (prefix, localName, namespaceURI );
  		}
  
  		public XmlAttribute CreateAttribute (string qualifiedName, string namespaceURI)
  		{
  			string prefix;
  			string localName;
  
  			ParseName (qualifiedName, out prefix, out localName);
  
  			return CreateAttribute (prefix, localName, namespaceURI);
  		}
  
  		public virtual XmlAttribute CreateAttribute (string prefix, string localName, string namespaceURI)
  		{
  			if ((localName == null) || (localName == String.Empty))
  				throw new ArgumentException ("The attribute local name cannot be empty.");
  
  			return new XmlAttribute (prefix, localName, namespaceURI, this, false, true);
  		}
  
  		internal XmlAttribute CreateAttribute (string prefix, string localName, string namespaceURI, bool atomizedNames, bool checkNamespace)
  		{
  			if (optimal_create_attribute)
  				return new XmlAttribute (prefix, localName, namespaceURI, this, atomizedNames, checkNamespace);
  			else
  				return CreateAttribute (prefix, localName, namespaceURI);
  		}
  
  		public virtual XmlCDataSection CreateCDataSection (string data)
  		{
  			return new XmlCDataSection (data, this);
  		}
  
  		public virtual XmlComment CreateComment (string data)
  		{
  			return new XmlComment (data, this);
  		}
  
  		protected internal virtual XmlAttribute CreateDefaultAttribute (string prefix, string localName, string namespaceURI)
  		{
  			XmlAttribute attr = CreateAttribute (prefix, localName, namespaceURI);
  			attr.isDefault = true;
  			return attr;
  		}
  
  		public virtual XmlDocumentFragment CreateDocumentFragment ()
  		{
  			return new XmlDocumentFragment (this);
  		}
  
  		[PermissionSet (SecurityAction.InheritanceDemand, Unrestricted = true)]
  		public virtual XmlDocumentType CreateDocumentType (string name, string publicId,
  								   string systemId, string internalSubset)
  		{
  			return new XmlDocumentType (name, publicId, systemId, internalSubset, this);
  		}
  
  		private XmlDocumentType CreateDocumentType (DTDObjectModel dtd)
  		{
  			return new XmlDocumentType (dtd, this);
  		}
  
  		public XmlElement CreateElement (string name)
  		{
  			return CreateElement (name, String.Empty);
  		}
  
  		public XmlElement CreateElement (
  			string qualifiedName, 
  			string namespaceURI)
  		{
  			string prefix;
  			string localName;
  
  			ParseName (qualifiedName, out prefix, out localName);
  			
  			return CreateElement (prefix, localName, namespaceURI);
  		}
  
  		public virtual XmlElement CreateElement (
  			string prefix,
  			string localName,
  			string namespaceURI)
  		{
  			// LAMESPEC: MS.NET has a weird behavior that they can Load() from XmlTextReader 
  			// whose Namespaces = false, but their CreateElement() never allows qualified name.
  			// I leave it as it is.
  			return new XmlElement (prefix != null ? prefix : String.Empty, localName, namespaceURI != null ? namespaceURI : String.Empty, this, false);
  		}
  
  		internal XmlElement CreateElement (
  			string prefix,
  			string localName,
  			string namespaceURI,
  			bool nameAtomized)
  		{
  			if ((localName == null) || (localName == String.Empty))
  				throw new ArgumentException ("The local name for elements or attributes cannot be null or an empty string.");
  			if (optimal_create_element)
  				// LAMESPEC: MS.NET has a weird behavior that they can Load() from XmlTextReader 
  				// whose Namespaces = false, but their CreateElement() never allows qualified name.
  				// I leave it as it is.
  				return new XmlElement (prefix != null ? prefix : String.Empty, localName, namespaceURI != null ? namespaceURI : String.Empty, this, nameAtomized);
  			else
  				return CreateElement (prefix, localName, namespaceURI);
  		}
  
  		public virtual XmlEntityReference CreateEntityReference (string name)
  		{
  			return new XmlEntityReference (name, this);
  		}
  
  #if NET_2_0
  		public override XPathNavigator CreateNavigator ()
  		{
  			return CreateNavigator (this);
  		}
  #endif
  
  		protected internal virtual XPathNavigator CreateNavigator (XmlNode node)
  		{
  #if NET_2_0
  			return new XPathEditableDocument (node).CreateNavigator ();
  #else
  			return new XmlDocumentNavigator (node);
  #endif
  		}
  
  		public virtual XmlNode CreateNode (
  			string nodeTypeString,
  			string name,
  			string namespaceURI)
  		{
  			return CreateNode (GetNodeTypeFromString (nodeTypeString), name, namespaceURI);
  		}
  
  		public virtual XmlNode CreateNode (
  			XmlNodeType type,
  			string name,
  			string namespaceURI)
  		{
  			string prefix = null;
  			string localName = name;
  
  			if ((type == XmlNodeType.Attribute) || (type == XmlNodeType.Element) || (type == XmlNodeType.EntityReference))
  				ParseName (name, out prefix, out localName);
  			
  			return CreateNode (type, prefix, localName, namespaceURI);
  		}
  
  		public virtual XmlNode CreateNode (
  			XmlNodeType type,
  			string prefix,
  			string name,
  			string namespaceURI)
  		{
  			switch (type) {
  				case XmlNodeType.Attribute: return CreateAttribute (prefix, name, namespaceURI);
  				case XmlNodeType.CDATA: return CreateCDataSection (null);
  				case XmlNodeType.Comment: return CreateComment (null);
  				case XmlNodeType.Document: return new XmlDocument ();
  				case XmlNodeType.DocumentFragment: return CreateDocumentFragment ();
  				case XmlNodeType.DocumentType: return CreateDocumentType (null, null, null, null);
  				case XmlNodeType.Element: return CreateElement (prefix, name, namespaceURI);
  				case XmlNodeType.EntityReference: return CreateEntityReference (null);
  				case XmlNodeType.ProcessingInstruction: return CreateProcessingInstruction (null, null);
  				case XmlNodeType.SignificantWhitespace: return CreateSignificantWhitespace (String.Empty);
  				case XmlNodeType.Text: return CreateTextNode (null);
  				case XmlNodeType.Whitespace: return CreateWhitespace (String.Empty);
  				case XmlNodeType.XmlDeclaration: return CreateXmlDeclaration ("1.0", null, null);
  				default:
  #if NET_2_0
  					throw new ArgumentException (
  #else // makes less sense
  					throw new ArgumentOutOfRangeException (
  #endif
  						String.Format("{0}\nParameter name: {1}",
  							 "Specified argument was out of the range of valid values", type.ToString ()));
  			}
  		}
  
  		public virtual XmlProcessingInstruction CreateProcessingInstruction (
  			string target,
  			string data)
  		{
  			return new XmlProcessingInstruction (target, data, this);
  		}
  
  		public virtual XmlSignificantWhitespace CreateSignificantWhitespace (string text)
  		{
  
gt: 			if (!XmlChar.IsWhitespace (text))