2005-01-31 Zoltan Varga <vargaz@freemail.hu>
[mono.git] / mcs / class / System.XML / System.Xml / XmlDocument.cs
index 7337acc697612c8e0753c4678700aeba92861094..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
 {
@@ -35,6 +60,10 @@ namespace System.Xml
                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
@@ -60,8 +89,12 @@ 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 ();
                }
@@ -107,7 +140,8 @@ namespace System.Xml
 
                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;
                                }
@@ -148,6 +182,10 @@ namespace System.Xml
                        get { return "#document"; }
                }
 
+               internal XmlNameEntryCache NameCache {
+                       get { return nameCache; }
+               }
+
                public XmlNameTable NameTable {
                        get { return nameTable; }
                }
@@ -200,6 +238,13 @@ namespace System.Xml
                        }
                }
 
+#if NET_2_0
+               public XmlSchemaSet Schemas {
+                       get { return schemas; }
+                       set { schemas = value; }
+               }
+#endif
+
                #endregion
 
                #region Methods
@@ -210,13 +255,13 @@ namespace System.Xml
 
                public override XmlNode CloneNode (bool deep)
                {
-                       XmlDocument doc = implementation.CreateDocument ();
+                       XmlDocument doc = implementation != null ? implementation.CreateDocument () : new XmlDocument ();
                        doc.baseURI = baseURI;
 
                        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;
                }
@@ -317,11 +362,9 @@ 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.");
-                       // FIXME: MS.NET has a weird behavior that they can Load() from XmlTextReader 
+                       // 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.
-                       if (!XmlChar.IsName (localName))
-                               throw new ArgumentException ("Invalid name.", "localName");
                        return new XmlElement (prefix != null ? prefix : String.Empty, localName, namespaceURI != null ? namespaceURI : String.Empty, this, false);
                }
 
@@ -332,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 (
@@ -391,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);
@@ -405,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);
                }
@@ -424,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);
@@ -483,12 +529,15 @@ namespace System.Xml
 
                public virtual XmlNode ImportNode (XmlNode node, bool deep)
                {
+                       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);
-                               foreach (XmlNode child in srcAtt.ChildNodes)
-                                       dstAtt.AppendChild (this.ImportNode (child, deep));
+                               for (int i = 0; i < srcAtt.ChildNodes.Count; i++)
+                                       dstAtt.AppendChild (this.ImportNode (srcAtt.ChildNodes [i], deep));
                                return dstAtt;
 
                        case XmlNodeType.CDATA:
@@ -503,8 +552,8 @@ namespace System.Xml
                        case XmlNodeType.DocumentFragment:
                                XmlDocumentFragment df = this.CreateDocumentFragment ();
                                if(deep)
-                                       foreach(XmlNode n in node.ChildNodes)
-                                               df.AppendChild (this.ImportNode (n, deep));
+                                       for (int i = 0; i < node.ChildNodes.Count; i++)
+                                               df.AppendChild (this.ImportNode (node.ChildNodes [i], deep));
                                return df;
 
                        case XmlNodeType.DocumentType:
@@ -513,12 +562,14 @@ namespace System.Xml
                        case XmlNodeType.Element:
                                XmlElement src = (XmlElement)node;
                                XmlElement dst = this.CreateElement (src.Prefix, src.LocalName, src.NamespaceURI);
-                               foreach(XmlAttribute attr in src.Attributes)
+                               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));
+                                               dst.SetAttributeNode ((XmlAttribute) this.ImportNode (attr, deep));
+                               }
                                if(deep)
-                                       foreach(XmlNode n in src.ChildNodes)
-                                               dst.AppendChild (this.ImportNode (n, deep));
+                                       for (int i = 0; i < src.ChildNodes.Count; i++)
+                                               dst.AppendChild (this.ImportNode (src.ChildNodes [i], deep));
                                return dst;
 
                        case XmlNodeType.EndElement:
@@ -556,25 +607,27 @@ namespace System.Xml
 
                public virtual void Load (Stream inStream)
                {
-                       XmlTextReader reader = new XmlTextReader (inStream);
+                       XmlTextReader reader = new XmlTextReader (inStream, NameTable);
                        reader.XmlResolver = resolver;
                        Load (reader);
                }
 
                public virtual void Load (string filename)
                {
-                       XmlTextReader xr = new XmlTextReader (filename);
+                       XmlTextReader xr = null;
                        try {
+                               xr = new XmlTextReader (filename, NameTable);
                                xr.XmlResolver = resolver;
                                Load (xr);
                        } finally {
-                               xr.Close ();
+                               if (xr != null)
+                                       xr.Close ();
                        }
                }
 
                public virtual void Load (TextReader txtReader)
                {
-                       XmlTextReader xr = new XmlTextReader (txtReader);
+                       XmlTextReader xr = new XmlTextReader (txtReader, NameTable);
                        xr.XmlResolver = resolver;
                        Load (xr);
                }
@@ -598,6 +651,10 @@ namespace System.Xml
                                        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;
                        }
@@ -606,7 +663,9 @@ namespace System.Xml
                public virtual void LoadXml (string xml)
                {
                        XmlTextReader xmlReader = new XmlTextReader (
-                               xml, XmlNodeType.Document, null);
+                               xml,
+                               XmlNodeType.Document,
+                               new XmlParserContext (NameTable, null, null, XmlSpace.None));
                        try {
                                xmlReader.XmlResolver = resolver;
                                Load (xmlReader);
@@ -615,20 +674,22 @@ namespace System.Xml
                        }
                }
 
-               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)
@@ -677,21 +738,24 @@ namespace System.Xml
                }
 
                // 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, 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;
@@ -702,9 +766,7 @@ namespace System.Xml
                {
                        while (reader.ReadAttributeValue ()) {
                                if (reader.NodeType == XmlNodeType.EntityReference)
-                                       // FIXME: if DocumentType is available, then try to resolve it.
                                        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));
@@ -739,6 +801,10 @@ namespace System.Xml
 
                        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.
@@ -780,15 +846,6 @@ namespace System.Xml
 
                        case XmlNodeType.DocumentType:
                                DTDObjectModel dtd = null;
-                               XmlTextReader xtReader = reader as XmlTextReader;
-                               if (xtReader != null)
-                                       dtd = xtReader.DTD;
-                               XmlNodeReader xnReader = reader as XmlNodeReader;
-                               if (xnReader != null)
-                                       dtd = xnReader.GetInternalParserContext ().Dtd;
-                               XmlValidatingReader xvReader = reader as XmlValidatingReader;
-                               if (xvReader != null)
-                                       dtd = xvReader.GetInternalParserContext ().Dtd;
                                IHasXmlParserContext ctxReader = reader as IHasXmlParserContext;
                                if (ctxReader != null)
                                        dtd = ctxReader.ParserContext.Dtd;
@@ -831,7 +888,7 @@ namespace System.Xml
                {
                        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;
                }
@@ -841,10 +898,11 @@ namespace System.Xml
                        idTable.Remove (id);
                }
 
-               public virtual void Save(Stream outStream)
+               public virtual void Save (Stream outStream)
                {
                        XmlTextWriter xmlWriter = new XmlTextWriter (outStream, TextEncoding);
-                       xmlWriter.Formatting = Formatting.Indented;
+                       if (!PreserveWhitespace)
+                               xmlWriter.Formatting = Formatting.Indented;
                        WriteContentTo (xmlWriter);
                        xmlWriter.Flush ();
                }
@@ -853,7 +911,8 @@ namespace System.Xml
                {
                        XmlTextWriter xmlWriter = new XmlTextWriter (filename, TextEncoding);
                        try {
-                               xmlWriter.Formatting = Formatting.Indented;
+                               if (!PreserveWhitespace)
+                                       xmlWriter.Formatting = Formatting.Indented;
                                WriteContentTo (xmlWriter);
                        } finally {
                                xmlWriter.Close ();
@@ -863,8 +922,12 @@ namespace System.Xml
                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 ();
                }
 
@@ -884,9 +947,8 @@ namespace System.Xml
 
                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)
@@ -912,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
        }
 }