2005-01-31 Zoltan Varga <vargaz@freemail.hu>
[mono.git] / mcs / class / System.XML / System.Xml / XmlDocument.cs
index e5ce1c5eb17aed096fd08b3c923ab482ae7bf2ef..375e8a0eb716bef03a721e22c7e83e2b3a1a722e 100644 (file)
 //   Atsushi Enomoto
 //
 
+//
+// 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;
+using System.Globalization;\r
 using System.IO;
 using System.Text;
 using System.Xml.XPath;
 using System.Diagnostics;
 using System.Collections;
 using Mono.Xml;
-using Mono.Xml.Native;
+#if NET_2_0
+using System.Xml.Schema;
+using Mono.Xml.XPath;
+#endif
 
 namespace System.Xml
 {
@@ -29,13 +54,22 @@ namespace System.Xml
        {
                #region Fields
 
-               XmlLinkedNode lastLinkedChild;
                XmlNameTable nameTable;
                string baseURI = String.Empty;
                XmlImplementation implementation;
                bool preserveWhitespace = false;
                XmlResolver resolver;
                Hashtable idTable = new Hashtable ();
+               XmlNameEntryCache nameCache = new XmlNameEntryCache ();
+#if NET_2_0
+               XmlSchemaSet schemas;
+#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
 
@@ -55,9 +89,14 @@ namespace System.Xml
 
                XmlDocument (XmlImplementation impl, XmlNameTable nt) : base (null)
                {
-                       implementation = (impl != null) ? impl : new XmlImplementation ();
-                       nameTable = (nt != null) ? nt : implementation.internalNameTable;
+                       if (impl == null)
+                               implementation = new XmlImplementation ();
+                       else
+                               implementation = impl;
+
+                       nameTable = (nt != null) ? nt : implementation.InternalNameTable;
                        AddDefaultNameTableKeys ();
+                       resolver = new XmlUrlResolver ();
                }
                #endregion
 
@@ -99,10 +138,10 @@ namespace System.Xml
                        }
                }
 
-               [MonoTODO("It doesn't have internal subset object model.")]
                public virtual XmlDocumentType DocumentType {
                        get {
-                               foreach(XmlNode n in this.ChildNodes) {
+                               for (int i = 0; i < ChildNodes.Count; i++) {
+                                       XmlNode n = ChildNodes [i];
                                        if(n.NodeType == XmlNodeType.DocumentType)
                                                return (XmlDocumentType)n;
                                }
@@ -127,16 +166,14 @@ namespace System.Xml
                        get { return false; }
                }
 
-               internal override XmlLinkedNode LastLinkedChild {
-                       get     {
-                               return lastLinkedChild;
-                       }
-
-                       set {
-                               lastLinkedChild = value;
+               internal bool IsStandalone {
+                       get {
+                               return FirstChild != null &&
+                                       FirstChild.NodeType == XmlNodeType.XmlDeclaration &&
+                                       ((XmlDeclaration) this.FirstChild).Standalone == "yes";
                        }
                }
-               
+
                public override string LocalName {
                        get { return "#document"; }
                }
@@ -145,6 +182,10 @@ namespace System.Xml
                        get { return "#document"; }
                }
 
+               internal XmlNameEntryCache NameCache {
+                       get { return nameCache; }
+               }
+
                public XmlNameTable NameTable {
                        get { return nameTable; }
                }
@@ -168,6 +209,10 @@ namespace System.Xml
                        set { preserveWhitespace = value; }
                }
 
+               internal XmlResolver Resolver {
+                       get { return resolver; }
+               }
+
                internal override string XmlLang {
                        get { return String.Empty; }
                }
@@ -181,6 +226,24 @@ namespace System.Xml
                                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 XmlSchemaSet Schemas {
+                       get { return schemas; }
+                       set { schemas = value; }
+               }
+#endif
 
                #endregion
 
@@ -192,22 +255,31 @@ namespace System.Xml
 
                public override XmlNode CloneNode (bool deep)
                {
-                       XmlDocument doc = implementation.CreateDocument ();
+                       XmlDocument doc = implementation != null ? implementation.CreateDocument () : new XmlDocument ();
                        doc.baseURI = baseURI;
 
-                       doc.PreserveWhitespace = PreserveWhitespace;    // required?
                        if(deep)
                        {
-                               foreach(XmlNode n in ChildNodes)
-                                       doc.AppendChild (doc.ImportNode (n, deep));
+                               for (int i = 0; i < ChildNodes.Count; i++)
+                                       doc.AppendChild (doc.ImportNode (ChildNodes [i], deep));
                        }
                        return doc;
                }
 
                public XmlAttribute CreateAttribute (string name)
                {
-                       return CreateAttribute (name,
-                               name == "xmlns" ? "http://www.w3.org/2000/xmlns/" : String.Empty);
+                       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)
@@ -221,11 +293,16 @@ namespace System.Xml
                }
 
                public virtual XmlAttribute CreateAttribute (string prefix, string localName, string namespaceURI)
+               {
+                       return CreateAttribute (prefix, localName, namespaceURI, false, true);
+               }
+
+               internal XmlAttribute CreateAttribute (string prefix, string localName, string namespaceURI, bool atomizedNames, bool checkNamespace)
                {
                        if ((localName == null) || (localName == String.Empty))
                                throw new ArgumentException ("The attribute local name cannot be empty.");
 
-                       return new XmlAttribute (prefix, localName, namespaceURI, this);
+                       return new XmlAttribute (prefix, localName, namespaceURI, this, atomizedNames, checkNamespace);
                }
 
                public virtual XmlCDataSection CreateCDataSection (string data)
@@ -256,9 +333,9 @@ namespace System.Xml
                        return new XmlDocumentType (name, publicId, systemId, internalSubset, this);
                }
 
-               private XmlDocumentType CreateDocumentType (XmlTextReader reader)
+               private XmlDocumentType CreateDocumentType (DTDObjectModel dtd)
                {
-                       return new XmlDocumentType (reader, this);
+                       return new XmlDocumentType (dtd, this);
                }
 
                public XmlElement CreateElement (string name)
@@ -285,8 +362,10 @@ namespace System.Xml
                {
                        if ((localName == null) || (localName == String.Empty))
                                throw new ArgumentException ("The local name for elements or attributes cannot be null or an empty string.");
-                       CheckName (localName);
-                       return new XmlElement (prefix != null ? prefix : String.Empty, localName, namespaceURI != null ? namespaceURI : String.Empty, this);
+                       // 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);
                }
 
                public virtual XmlEntityReference CreateEntityReference (string name)
@@ -296,7 +375,11 @@ namespace System.Xml
 
                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 (
@@ -331,7 +414,7 @@ namespace System.Xml
                                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 (); // TODO - test to see which constructor to use, i.e. use existing NameTable or not.
+                               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);
@@ -355,8 +438,7 @@ namespace System.Xml
 
                public virtual XmlSignificantWhitespace CreateSignificantWhitespace (string text)
                {
-                       foreach (char c in text)
-                               if ((c != ' ') && (c != '\r') && (c != '\n') && (c != '\t'))
+                       if (!XmlChar.IsWhitespace (text))
                                    throw new ArgumentException ("Invalid whitespace characters.");
                         
                        return new XmlSignificantWhitespace (text, this);
@@ -369,9 +451,8 @@ namespace System.Xml
 
                public virtual XmlWhitespace CreateWhitespace (string text)
                {
-                       foreach (char c in text)
-                               if ((c != ' ') && (c != '\r') && (c != '\n') && (c != '\t'))
-                                   throw new ArgumentException ("Invalid whitespace characters.");
+                       if (!XmlChar.IsWhitespace (text))
+                           throw new ArgumentException ("Invalid whitespace characters.");
                         
                        return new XmlWhitespace (text, this);
                }
@@ -388,11 +469,12 @@ namespace System.Xml
                        return new XmlDeclaration (version, encoding, standalone, this);
                }
 
-               [MonoTODO]
                // FIXME: Currently XmlAttributeCollection.SetNamedItem() does
                // add to the identity table, but in fact I delayed identity
                // check on GetIdenticalAttribute. To make such way complete,
                // we have to use MultiMap, not Hashtable.
+               //
+               // Well, MS.NET is also fragile around here.
                public virtual XmlElement GetElementById (string elementId)
                {
                        XmlAttribute attr = GetIdenticalAttribute (elementId);
@@ -402,38 +484,14 @@ namespace System.Xml
                public virtual XmlNodeList GetElementsByTagName (string name)
                {
                        ArrayList nodeArrayList = new ArrayList ();
-                       this.searchNodesRecursively (this, name, nodeArrayList);
+                       this.SearchDescendantElements (name, name == "*", nodeArrayList);
                        return new XmlNodeArrayList (nodeArrayList);
                }
 
-               private void searchNodesRecursively (XmlNode argNode, string argName, 
-                       ArrayList argArrayList)
-               {
-                       XmlNodeList xmlNodeList = argNode.ChildNodes;
-                       foreach (XmlNode node in xmlNodeList){
-                               if (node.Name.Equals (argName))
-                                       argArrayList.Add (node);
-                               else    
-                                       this.searchNodesRecursively (node, argName, argArrayList);
-                       }
-               }
-
-               private void searchNodesRecursively (XmlNode argNode, string argName, string argNamespaceURI, 
-                       ArrayList argArrayList)
-               {
-                       XmlNodeList xmlNodeList = argNode.ChildNodes;
-                       foreach (XmlNode node in xmlNodeList){
-                               if (node.LocalName.Equals (argName) && node.NamespaceURI.Equals (argNamespaceURI))
-                                       argArrayList.Add (node);
-                               else    
-                                       this.searchNodesRecursively (node, argName, argNamespaceURI, argArrayList);
-                       }
-               }
-
                public virtual XmlNodeList GetElementsByTagName (string localName, string namespaceURI)
                {
                        ArrayList nodeArrayList = new ArrayList ();
-                       this.searchNodesRecursively (this, localName, namespaceURI, nodeArrayList);
+                       this.SearchDescendantElements (localName, localName == "*", namespaceURI, namespaceURI == "*", nodeArrayList);
                        return new XmlNodeArrayList (nodeArrayList);
                }
 
@@ -462,127 +520,116 @@ namespace System.Xml
                        XmlAttribute attr = this.idTable [id] as XmlAttribute;
                        if (attr == null)
                                return null;
-//                     if (attr.OwnerElement == null || !attr.OwnerElement.IsRooted) {
-                        if (attr.OwnerElement == null) {
-                               idTable.Remove (id);
+                       if (attr.OwnerElement == null || !attr.OwnerElement.IsRooted) {
+//                             idTable.Remove (id);
                                return null;
                        }
                        return attr;
                }
 
-               [MonoTODO("default attributes (of imported doc); Entity; Notation")]
                public virtual XmlNode ImportNode (XmlNode node, bool deep)
                {
-                       switch(node.NodeType)
-                       {
-                               case XmlNodeType.Attribute:
-                                       {
-                                               XmlAttribute src_att = node as XmlAttribute;
-                                               XmlAttribute dst_att = this.CreateAttribute (src_att.Prefix, src_att.LocalName, src_att.NamespaceURI);
-                                               dst_att.Value = src_att.Value;  // always explicitly specified (whether source is specified or not)
-                                               return dst_att;
-                                       }
-
-                               case XmlNodeType.CDATA:
-                                       return this.CreateCDataSection (node.Value);
-
-                               case XmlNodeType.Comment:
-                                       return this.CreateComment (node.Value);
-
-                               case XmlNodeType.Document:
-                                       throw new XmlException ("Document cannot be imported.");
-
-                               case XmlNodeType.DocumentFragment:
-                                       {
-                                               XmlDocumentFragment df = this.CreateDocumentFragment ();
-                                               if(deep)
-                                               {
-                                                       foreach(XmlNode n in node.ChildNodes)
-                                                       {
-                                                               df.AppendChild (this.ImportNode (n, deep));
-                                                       }
-                                               }
-                                               return df;
-                                       }
-
-                               case XmlNodeType.DocumentType:
-                                       throw new XmlException ("DocumentType cannot be imported.");
-
-                               case XmlNodeType.Element:
-                                       {
-                                               XmlElement src = (XmlElement)node;
-                                               XmlElement dst = this.CreateElement (src.Prefix, src.LocalName, src.NamespaceURI);
-                                               foreach(XmlAttribute attr in src.Attributes)
-                                               {
-                                                       if(attr.Specified)      // copies only specified attributes
-                                                               dst.SetAttributeNode ((XmlAttribute)this.ImportNode (attr, deep));
-                                                       if(DocumentType != null)
-                                                       {
-                                                               // TODO: create default attribute values
-                                                       }
-                                               }
-                                               if(deep)
-                                               {
-                                                       foreach(XmlNode n in src.ChildNodes)
-                                                               dst.AppendChild (this.ImportNode (n, deep));
-                                               }
-                                               return dst;
-                                       }
-
-                               case XmlNodeType.EndElement:
-                                       throw new XmlException ("Illegal ImportNode call for NodeType.EndElement");
-                               case XmlNodeType.EndEntity:
-                                       throw new XmlException ("Illegal ImportNode call for NodeType.EndEntity");
-
-                               case XmlNodeType.Entity:
-                                       throw new NotImplementedException ();   // TODO
-
-                               case XmlNodeType.EntityReference:
-                                       return this.CreateEntityReference (node.Name);
-
-                               case XmlNodeType.None:
-                                       throw new XmlException ("Illegal ImportNode call for NodeType.None");
-
-                               case XmlNodeType.Notation:
-                                       throw new NotImplementedException ();   // TODO
-
-                               case XmlNodeType.ProcessingInstruction:
-                                       XmlProcessingInstruction pi = node as XmlProcessingInstruction;
-                                       return this.CreateProcessingInstruction (pi.Target, pi.Data);
-
-                               case XmlNodeType.SignificantWhitespace:
-                                       return this.CreateSignificantWhitespace (node.Value);
-
-                               case XmlNodeType.Text:
-                                       return this.CreateTextNode (node.Value);
-
-                               case XmlNodeType.Whitespace:
-                                       return this.CreateWhitespace (node.Value);
-
-                               case XmlNodeType.XmlDeclaration:
-                                       XmlDeclaration srcDecl = node as XmlDeclaration;
-                                       return this.CreateXmlDeclaration (srcDecl.Version, srcDecl.Encoding, srcDecl.Standalone);
+                       if (node == null)
+                               throw new NullReferenceException ("Null node cannot be imported.");
+
+                       switch (node.NodeType) {
+                       case XmlNodeType.Attribute:
+                               XmlAttribute srcAtt = node as XmlAttribute;
+                               XmlAttribute dstAtt = this.CreateAttribute (srcAtt.Prefix, srcAtt.LocalName, srcAtt.NamespaceURI);
+                               for (int i = 0; i < srcAtt.ChildNodes.Count; i++)
+                                       dstAtt.AppendChild (this.ImportNode (srcAtt.ChildNodes [i], deep));
+                               return dstAtt;
+
+                       case XmlNodeType.CDATA:
+                               return this.CreateCDataSection (node.Value);
+
+                       case XmlNodeType.Comment:
+                               return this.CreateComment (node.Value);
+
+                       case XmlNodeType.Document:
+                               throw new XmlException ("Document cannot be imported.");
+
+                       case XmlNodeType.DocumentFragment:
+                               XmlDocumentFragment df = this.CreateDocumentFragment ();
+                               if(deep)
+                                       for (int i = 0; i < node.ChildNodes.Count; i++)
+                                               df.AppendChild (this.ImportNode (node.ChildNodes [i], deep));
+                               return df;
+
+                       case XmlNodeType.DocumentType:
+                               throw new XmlException ("DocumentType cannot be imported.");
+
+                       case XmlNodeType.Element:
+                               XmlElement src = (XmlElement)node;
+                               XmlElement dst = this.CreateElement (src.Prefix, src.LocalName, src.NamespaceURI);
+                               for (int i = 0; i < src.Attributes.Count; i++) {
+                                       XmlAttribute attr = src.Attributes [i];
+                                       if(attr.Specified)      // copies only specified attributes
+                                               dst.SetAttributeNode ((XmlAttribute) this.ImportNode (attr, deep));
+                               }
+                               if(deep)
+                                       for (int i = 0; i < src.ChildNodes.Count; i++)
+                                               dst.AppendChild (this.ImportNode (src.ChildNodes [i], deep));
+                               return dst;
 
-                               default:
-                                       throw new NotImplementedException ();
+                       case XmlNodeType.EndElement:
+                               throw new XmlException ("Illegal ImportNode call for NodeType.EndElement");
+                       case XmlNodeType.EndEntity:
+                               throw new XmlException ("Illegal ImportNode call for NodeType.EndEntity");
+
+                       case XmlNodeType.EntityReference:
+                               return this.CreateEntityReference (node.Name);
+
+                       case XmlNodeType.None:
+                               throw new XmlException ("Illegal ImportNode call for NodeType.None");
+
+                       case XmlNodeType.ProcessingInstruction:
+                               XmlProcessingInstruction pi = node as XmlProcessingInstruction;
+                               return this.CreateProcessingInstruction (pi.Target, pi.Data);
+
+                       case XmlNodeType.SignificantWhitespace:
+                               return this.CreateSignificantWhitespace (node.Value);
+
+                       case XmlNodeType.Text:
+                               return this.CreateTextNode (node.Value);
+
+                       case XmlNodeType.Whitespace:
+                               return this.CreateWhitespace (node.Value);
+
+                       case XmlNodeType.XmlDeclaration:
+                               XmlDeclaration srcDecl = node as XmlDeclaration;
+                               return this.CreateXmlDeclaration (srcDecl.Version, srcDecl.Encoding, srcDecl.Standalone);
+
+                       default:
+                               throw new InvalidOperationException ("Cannot import specified node type: " + node.NodeType);
                        }
                }
 
                public virtual void Load (Stream inStream)
                {
-                       Load (new XmlTextReader (inStream));
+                       XmlTextReader reader = new XmlTextReader (inStream, NameTable);
+                       reader.XmlResolver = resolver;
+                       Load (reader);
                }
 
                public virtual void Load (string filename)
                {
-                       XmlReader xr = new XmlTextReader (filename);
-                       Load (xr);
-                       xr.Close ();
+                       XmlTextReader xr = null;
+                       try {
+                               xr = new XmlTextReader (filename, NameTable);
+                               xr.XmlResolver = resolver;
+                               Load (xr);
+                       } finally {
+                               if (xr != null)
+                                       xr.Close ();
+                       }
                }
 
                public virtual void Load (TextReader txtReader)
                {
-                       Load (new XmlTextReader (txtReader));
+                       XmlTextReader xr = new XmlTextReader (txtReader, NameTable);
+                       xr.XmlResolver = resolver;
+                       Load (xr);
                }
 
                public virtual void Load (XmlReader xmlReader)
@@ -595,34 +642,54 @@ namespace System.Xml
 
                        this.baseURI = xmlReader.BaseURI;
                        // create all contents with use of ReadNode()
-                       do {
-                               XmlNode n = ReadNode (xmlReader);
-                               if(n == null) break;
-                               AppendChild (n);
-                       } while (true);
+                       try {
+                               loadMode = true;
+                               do {
+                                       XmlNode n = ReadNode (xmlReader);
+                                       if (n == null)
+                                               break;
+                                       if (preserveWhitespace || n.NodeType != XmlNodeType.Whitespace)
+                                               AppendChild (n);
+                               } while (true);
+#if NET_2_0
+                               if (xmlReader.Settings != null)
+                                       schemas = xmlReader.Settings.Schemas;
+#endif
+                       } finally {
+                               loadMode = false;
+                       }
                }
 
                public virtual void LoadXml (string xml)
                {
-                       XmlReader xmlReader = new XmlTextReader (
-                               xml, XmlNodeType.Document, null);
-                       Load (xmlReader);
+                       XmlTextReader xmlReader = new XmlTextReader (
+                               xml,
+                               XmlNodeType.Document,
+                               new XmlParserContext (NameTable, null, null, XmlSpace.None));
+                       try {
+                               xmlReader.XmlResolver = resolver;
+                               Load (xmlReader);
+                       } finally {
+                               xmlReader.Close ();
+                       }
                }
 
-               internal void onNodeChanged (XmlNode node, XmlNode Parent)
+               internal void onNodeChanged (XmlNode node, XmlNode parent, string oldValue, string newValue)
                {
                        if (NodeChanged != null)
                                NodeChanged (node, new XmlNodeChangedEventArgs
                                        (XmlNodeChangedAction.Change,
-                                       node, Parent, Parent));
+                                       node, parent, oldValue, newValue));
                }
 
-               internal void onNodeChanging(XmlNode node, XmlNode Parent)
+               internal void onNodeChanging(XmlNode node, XmlNode parent, string oldValue, string newValue)
                {
+                       if (node.IsReadOnly)
+                               throw new ArgumentException ("Node is read-only.");
                        if (NodeChanging != null)
                                NodeChanging (node, new XmlNodeChangedEventArgs
                                        (XmlNodeChangedAction.Change,
-                                       node, Parent, Parent));
+                                       node, parent, oldValue, newValue));
                }
 
                internal void onNodeInserted (XmlNode node, XmlNode newParent)
@@ -670,54 +737,44 @@ namespace System.Xml
                        }
                }
 
-               // Checks that Element's name is valid
-               private void CheckName (String name)
-               {
-                       // TODO: others validations?
-                       if (name.IndexOf (" ") >= 0)
-                               throw new XmlException ("The ' ' characted cannot be included in a name");
-               }
-
                // Reads XmlReader and creates Attribute Node.
-               private XmlAttribute ReadAttributeNode(XmlReader reader)
+               private XmlAttribute ReadAttributeNode (XmlReader reader)
                {
-                       if(reader.NodeType == XmlNodeType.Element)
+                       if (reader.NodeType == XmlNodeType.Element)
                                reader.MoveToFirstAttribute ();
-                       else if(reader.NodeType != XmlNodeType.Attribute)
+                       else if (reader.NodeType != XmlNodeType.Attribute)
                                throw new InvalidOperationException (MakeReaderErrorMessage ("bad position to read attribute.", reader));
-                       XmlAttribute attribute = CreateAttribute (reader.Prefix, reader.LocalName, reader.NamespaceURI);
+                       XmlAttribute attribute = CreateAttribute (reader.Prefix, reader.LocalName, reader.NamespaceURI, false, false); // different NameTable
+#if NET_2_0
+                       if (reader.SchemaInfo != null)
+                               SchemaInfo = new XmlSchemaInfo (reader.SchemaInfo);
+#endif
                        ReadAttributeNodeValue (reader, attribute);
 
-                       // Keep the current reader position
-                       bool res;
-                       if (attribute.NamespaceURI == string.Empty || attribute.NamespaceURI == null)
-                               res = reader.MoveToAttribute (attribute.Name);
+                       // Keep the current reader position on attribute.
+                       if (attribute.NamespaceURI == null)
+                               reader.MoveToAttribute (attribute.Name);
                        else 
-                               res = reader.MoveToAttribute (attribute.LocalName, attribute.NamespaceURI);
+                               reader.MoveToAttribute (attribute.LocalName, attribute.NamespaceURI);
+                       if (reader.IsDefault)
+                               attribute.SetDefault ();
                        return attribute;
                }
 
                // Reads attribute from XmlReader and then creates attribute value children. XmlAttribute also uses this.
-               internal void ReadAttributeNodeValue(XmlReader reader, XmlAttribute attribute)
+               internal void ReadAttributeNodeValue (XmlReader reader, XmlAttribute attribute)
                {
-                       while(reader.ReadAttributeValue ()) {
-                               if(reader.NodeType == XmlNodeType.EntityReference)
-                                       // FIXME: if DocumentType is available, then try to resolve it.
+                       while (reader.ReadAttributeValue ()) {
+                               if (reader.NodeType == XmlNodeType.EntityReference)
                                        attribute.AppendChild (CreateEntityReference (reader.Name));
-                               // FIXME: else if(NodeType == EndEntity) -- reset BaseURI and so on -- ;
                                else
                                        // Children of Attribute is restricted to CharacterData and EntityReference (Comment is not allowed).
                                        attribute.AppendChild (CreateTextNode (reader.Value));
                        }
                }
 
-               [MonoTODO ("Child of entity is not simple Value string;Get prefix of NotationDecl")]
-               public virtual XmlNode ReadNode(XmlReader reader)
+               public virtual XmlNode ReadNode (XmlReader reader)
                {
-                       XmlNode resultNode = null;
-                       XmlNode newNode = null;
-                       XmlNode currentNode = null;
-
                        switch (reader.ReadState) {
                        case ReadState.Interactive:
                                break;
@@ -728,135 +785,110 @@ namespace System.Xml
                                return null;
                        }
 
-                       int startDepth = reader.Depth;
-                       bool ignoredWhitespace;
-                       bool reachedEOF = false;
-
-                       do {
-                               ignoredWhitespace = false;
-                               if (reader.ReadState != ReadState.Interactive)
-                                       if (reachedEOF)
-                                               throw new Exception ("XML Reader reached to end while reading node.");
-                                       else
-                                               reachedEOF = true;
-                               switch (reader.NodeType) {
-
-                               case XmlNodeType.Attribute:
-                                       newNode = ReadAttributeNode (reader);
-                                       break;
+                       XmlNode n;
+                       switch (reader.NodeType) {
 
-                               case XmlNodeType.CDATA:
-                                       newNode = CreateCDataSection (reader.Value);
-                                       if(currentNode != null)
-                                               currentNode.AppendChild (newNode);
-                                       break;
+                       case XmlNodeType.Attribute:
+                               return ReadAttributeNode (reader);
 
-                               case XmlNodeType.Comment:
-                                       newNode = CreateComment (reader.Value);
-                                       if(currentNode != null)
-                                               currentNode.AppendChild (newNode);
-                                       break;
+                       case XmlNodeType.CDATA:
+                               n = CreateCDataSection (reader.Value);
+                               break;
 
-                               case XmlNodeType.Element:
-                                       XmlElement element = CreateElement (reader.Prefix, reader.LocalName, reader.NamespaceURI);
-                                       element.IsEmpty = reader.IsEmptyElement;
-                                       if(currentNode != null)
-                                               currentNode.AppendChild (element);
-                                       else
-                                               resultNode = element;
+                       case XmlNodeType.Comment:
+                               n = CreateComment (reader.Value);
+                               break;
 
-                                       // set the element's attributes.
-                                       while (reader.MoveToNextAttribute ()) {
+                       case XmlNodeType.Element:
+                               XmlElement element = CreateElement (reader.Prefix, reader.LocalName, reader.NamespaceURI);
+#if NET_2_0
+                               if (reader.SchemaInfo != null)
+                                       SchemaInfo = new XmlSchemaInfo (reader.SchemaInfo);
+#endif
+                               element.IsEmpty = reader.IsEmptyElement;
+
+                               // set the element's attributes.
+                               if (reader.MoveToFirstAttribute ()) {
+                                       do {
                                                element.SetAttributeNode (ReadAttributeNode (reader));
-                                       }
-
+                                       } while (reader.MoveToNextAttribute ());
                                        reader.MoveToElement ();
+                               }
 
-                                       if (!reader.IsEmptyElement)
-                                               currentNode = element;
+                               int depth = reader.Depth;
 
+                               if (element.IsEmpty) {
+                                       n = element;
                                        break;
+                               }
 
-                               case XmlNodeType.EndElement:
-                                       if (currentNode == null)
-                                               throw new XmlException ("Unexpected end element.");
-                                       else if (currentNode.Name != reader.Name)
-                                               throw new XmlException (reader as IXmlLineInfo, String.Format ("mismatch end tag. Expected {0} but found {1}", currentNode.Name, reader.Name));
-                                       currentNode = currentNode.ParentNode;
-                                       break;
+                               reader.Read ();
+                               while (reader.Depth > depth) {
+                                       n = ReadNode (reader);
+                                       if (preserveWhitespace || n.NodeType != XmlNodeType.Whitespace)
+                                               element.AppendChild (n);
+                               }
+                               n = element;
+                               break;
 
-                               case XmlNodeType.EndEntity:
-                                       break;  // no operation
+                       case XmlNodeType.ProcessingInstruction:
+                               n = CreateProcessingInstruction (reader.Name, reader.Value);
+                               break;
 
-                               case XmlNodeType.ProcessingInstruction:
-                                       newNode = CreateProcessingInstruction (reader.Name, reader.Value);
-                                       if(currentNode != null)
-                                               currentNode.AppendChild (newNode);
-                                       break;
+                       case XmlNodeType.Text:
+                               n = CreateTextNode (reader.Value);
+                               break;
 
-                               case XmlNodeType.Text:
-                                       newNode = CreateTextNode (reader.Value);
-                                       if(currentNode != null)
-                                               currentNode.AppendChild (newNode);
-                                       break;
+                       case XmlNodeType.XmlDeclaration:
+                               n = CreateXmlDeclaration ("1.0" , String.Empty, String.Empty);
+                               n.Value = reader.Value;
+                               break;
 
-                               case XmlNodeType.XmlDeclaration:
-                                       // empty strings are dummy, then gives over setting value contents to setter.
-                                       newNode = CreateXmlDeclaration ("1.0" , String.Empty, String.Empty);
-                                       ((XmlDeclaration)newNode).Value = reader.Value;
-                                       if(currentNode != null)
-                                               throw new XmlException (reader as IXmlLineInfo, "XmlDeclaration at invalid position.");
-                                       break;
+                       case XmlNodeType.DocumentType:
+                               DTDObjectModel dtd = null;
+                               IHasXmlParserContext ctxReader = reader as IHasXmlParserContext;
+                               if (ctxReader != null)
+                                       dtd = ctxReader.ParserContext.Dtd;
 
-                               case XmlNodeType.DocumentType:
-                                       // hack ;-)
-                                       XmlTextReader xtReader = reader as XmlTextReader;
-                                       if(xtReader == null)
-                                               newNode = CreateDocumentType (reader.Name, reader ["PUBLIC"], reader ["SYSTEM"], reader.Value);
-                                       else
-                                               newNode = CreateDocumentType (xtReader);
+                               if (dtd != null)
+                                       n = CreateDocumentType (dtd);
+                               else
+                                       n = CreateDocumentType (reader.Name, reader ["PUBLIC"], reader ["SYSTEM"], reader.Value);
+                               break;
 
-                                       if(currentNode != null)
-                                               throw new XmlException (reader as IXmlLineInfo, "XmlDocumentType at invalid position.");
-                                       break;
+                       case XmlNodeType.EntityReference:
+                               if (this.loadMode && this.DocumentType != null &&
+                                       DocumentType.Entities.GetNamedItem (reader.Name) == null)
+                                       throw new XmlException ("Reference to undeclared entity was found.");
 
-                               case XmlNodeType.EntityReference:
-                                       newNode = CreateEntityReference (reader.Name);
-                                       if(currentNode != null)
-                                               currentNode.AppendChild (newNode);
-                                       break;
+                               n = CreateEntityReference (reader.Name);
+                               break;
 
-                               case XmlNodeType.SignificantWhitespace:
-                                       newNode = CreateSignificantWhitespace (reader.Value);
-                                       if(currentNode != null)
-                                               currentNode.AppendChild (newNode);
-                                       break;
+                       case XmlNodeType.SignificantWhitespace:
+                               n = CreateSignificantWhitespace (reader.Value);
+                               break;
 
-                               case XmlNodeType.Whitespace:
-                                       if(PreserveWhitespace) {
-                                               newNode = CreateWhitespace (reader.Value);
-                                               if(currentNode != null)
-                                                       currentNode.AppendChild (newNode);
-                                       }
-                                       else
-                                               ignoredWhitespace = true;
-                                       break;
-                               }
-                               // Read next, except for reading attribute node.
-                               if (!(newNode is XmlAttribute) && !reader.Read ())
-                                       break;
-                       } while (ignoredWhitespace || reader.Depth > startDepth ||
-                               (reader.Depth == startDepth && reader.NodeType == XmlNodeType.EndElement));
-                       if (startDepth != reader.Depth && reader.EOF)
-                               throw new XmlException ("Unexpected end of xml reader.");
-                       return resultNode != null ? resultNode : newNode;
+                       case XmlNodeType.Whitespace:
+                               n = CreateWhitespace (reader.Value);
+                               break;
+
+                       case XmlNodeType.None:
+                               return null;
+
+                       default:
+                               // No idea why MS does throw NullReferenceException ;-P
+                               throw new NullReferenceException ("Unexpected node type " + reader.NodeType + ".");
+                       }
+
+                       reader.Read ();
+                       return n;
                }
 
                private string MakeReaderErrorMessage (string message, XmlReader reader)
                {
                        IXmlLineInfo li = reader as IXmlLineInfo;
                        if (li != null)
-                               return String.Format ("{0} Line number = {1}, Inline position = {2}.", message, li.LineNumber, li.LinePosition);
+                               return String.Format (CultureInfo.InvariantCulture, "{0} Line number = {1}, Inline position = {2}.", message, li.LineNumber, li.LinePosition);
                        else
                                return message;
                }
@@ -866,27 +898,36 @@ namespace System.Xml
                        idTable.Remove (id);
                }
 
-               public virtual void Save(Stream outStream)
+               public virtual void Save (Stream outStream)
                {
-                       XmlTextWriter xmlWriter = new XmlTextWriter (outStream, Encoding.UTF8);
-                       xmlWriter.Formatting = Formatting.Indented;
+                       XmlTextWriter xmlWriter = new XmlTextWriter (outStream, TextEncoding);
+                       if (!PreserveWhitespace)
+                               xmlWriter.Formatting = Formatting.Indented;
                        WriteContentTo (xmlWriter);
-                       xmlWriter.Close ();
+                       xmlWriter.Flush ();
                }
 
                public virtual void Save (string filename)
                {
-                       XmlTextWriter xmlWriter = new XmlTextWriter (filename, Encoding.UTF8);
-                       xmlWriter.Formatting = Formatting.Indented;
-                       WriteContentTo (xmlWriter);
-                       xmlWriter.Close ();
+                       XmlTextWriter xmlWriter = new XmlTextWriter (filename, TextEncoding);
+                       try {
+                               if (!PreserveWhitespace)
+                                       xmlWriter.Formatting = Formatting.Indented;
+                               WriteContentTo (xmlWriter);
+                       } finally {
+                               xmlWriter.Close ();
+                       }
                }
 
                public virtual void Save (TextWriter writer)
                {
                        XmlTextWriter xmlWriter = new XmlTextWriter (writer);
-                       xmlWriter.Formatting = Formatting.Indented;
+                       if (!PreserveWhitespace)
+                               xmlWriter.Formatting = Formatting.Indented;
+                       if (FirstChild != null && FirstChild.NodeType != XmlNodeType.XmlDeclaration)
+                               xmlWriter.WriteStartDocument ();
                        WriteContentTo (xmlWriter);
+                       xmlWriter.WriteEndDocument ();
                        xmlWriter.Flush ();
                }
 
@@ -895,15 +936,19 @@ namespace System.Xml
                        //
                        // This should preserve white space if PreserveWhiteSpace is true
                        //
+                       bool autoXmlDecl = FirstChild != null && FirstChild.NodeType != XmlNodeType.XmlDeclaration;
+                       if (autoXmlDecl)
+                               xmlWriter.WriteStartDocument ();
                        WriteContentTo (xmlWriter);
+                       if (autoXmlDecl)
+                               xmlWriter.WriteEndDocument ();
                        xmlWriter.Flush ();
                }
 
                public override void WriteContentTo (XmlWriter w)
                {
-                       foreach(XmlNode childNode in ChildNodes) {
-                               childNode.WriteTo (w);
-                       }
+                       for (int i = 0; i < ChildNodes.Count; i++)
+                               ChildNodes [i].WriteTo (w);
                }
 
                public override void WriteTo (XmlWriter w)
@@ -929,6 +974,39 @@ namespace System.Xml
                        nameTable.Add ("#document");
                        nameTable.Add ("#significant-whitespace");
                }
+
+#if NET_2_0
+               public void Validate (ValidationEventHandler handler)
+               {
+                       Validate (handler, this,
+                               XmlSchemaValidationFlags.IgnoreValidationWarnings);
+               }
+
+               public void Validate (ValidationEventHandler handler,
+                       XmlNode node)
+               {
+                       Validate (handler, node,
+                               XmlSchemaValidationFlags.IgnoreValidationWarnings |
+                               XmlSchemaValidationFlags.IgnoreIdentityConstraints);
+               }
+
+               private void Validate (ValidationEventHandler handler,
+                       XmlNode node, XmlSchemaValidationFlags flags)
+               {
+                       XmlReaderSettings settings = new XmlReaderSettings ();
+                       settings.NameTable = NameTable;
+                       settings.Schemas = schemas;
+                       settings.Schemas.XmlResolver = resolver;
+                       settings.XmlResolver = resolver;
+                       settings.ValidationFlags = flags;
+                       settings.ValidationType = ValidationType.Schema;
+                       XmlReader r = XmlReader.Create (
+                               new XmlNodeReader (node), settings);
+                       while (!r.EOF)
+                               r.Read ();
+               }
+#endif
+
                #endregion
        }
 }