2003-11-02 Pedro Mart�nez Juli� <yoros@wanadoo.es>
[mono.git] / mcs / class / System.XML / System.Xml / XmlDocument.cs
index fcf8d9b17b98b2b68f143a51db5e66d43264f648..c976b9726160e31ab4d7d4b3d341fef30d932683 100644 (file)
@@ -20,6 +20,7 @@ using System.Text;
 using System.Xml.XPath;
 using System.Diagnostics;
 using System.Collections;
+using Mono.Xml;
 using Mono.Xml.Native;
 
 namespace System.Xml
@@ -33,7 +34,8 @@ namespace System.Xml
                string baseURI = String.Empty;
                XmlImplementation implementation;
                bool preserveWhitespace = false;
-               WeakReference reusableXmlTextReader;
+               XmlResolver resolver;
+               Hashtable idTable = new Hashtable ();
 
                #endregion
 
@@ -56,6 +58,7 @@ namespace System.Xml
                        implementation = (impl != null) ? impl : new XmlImplementation ();
                        nameTable = (nt != null) ? nt : implementation.internalNameTable;
                        AddDefaultNameTableKeys ();
+                       resolver = new XmlUrlResolver ();
                }
                #endregion
 
@@ -83,19 +86,6 @@ namespace System.Xml
                        }
                }
 
-               // Used to read 'InnerXml's for its descendants at any place.
-               internal XmlTextReader ReusableReader {
-                       get {
-                               if(reusableXmlTextReader == null)
-                                       reusableXmlTextReader = new WeakReference (null);
-                               if(!reusableXmlTextReader.IsAlive) {
-                                       XmlTextReader reader = new XmlTextReader ((TextReader)null);
-                                       reusableXmlTextReader.Target = reader;
-                               }
-                               return (XmlTextReader)reusableXmlTextReader.Target;
-                       }
-               }
-
                public XmlElement DocumentElement {
                        get {
                                XmlNode node = FirstChild;
@@ -110,7 +100,6 @@ namespace System.Xml
                        }
                }
 
-               [MonoTODO("It doesn't have internal subset object model.")]
                public virtual XmlDocumentType DocumentType {
                        get {
                                foreach(XmlNode n in this.ChildNodes) {
@@ -138,6 +127,14 @@ namespace System.Xml
                        get { return false; }
                }
 
+               internal bool IsStandalone {
+                       get {
+                               return FirstChild != null &&
+                                       FirstChild.NodeType == XmlNodeType.XmlDeclaration &&
+                                       ((XmlDeclaration) this.FirstChild).Standalone == "yes";
+                       }
+               }
+
                internal override XmlLinkedNode LastLinkedChild {
                        get     {
                                return lastLinkedChild;
@@ -179,13 +176,16 @@ namespace System.Xml
                        set { preserveWhitespace = value; }
                }
 
+               internal XmlResolver Resolver {
+                       get { return resolver; }
+               }
+
                internal override string XmlLang {
                        get { return String.Empty; }
                }
 
-               [MonoTODO]
                public virtual XmlResolver XmlResolver {
-                       set { throw new NotImplementedException (); }
+                       set { resolver = value; }
                }
 
                internal override XmlSpace XmlSpace {
@@ -193,16 +193,31 @@ 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);
+                       }
+               }
 
                #endregion
 
                #region Methods
+               internal void AddIdenticalAttribute (XmlAttribute attr)
+               {
+                       idTable [attr.Value] = attr;
+               }
 
-               [MonoTODO("Should BaseURI be cloned?")]
                public override XmlNode CloneNode (bool deep)
                {
                        XmlDocument doc = implementation.CreateDocument ();
-                       doc.PreserveWhitespace = PreserveWhitespace;    // required?
+                       doc.baseURI = baseURI;
+
                        if(deep)
                        {
                                foreach(XmlNode n in ChildNodes)
@@ -213,7 +228,18 @@ namespace System.Xml
 
                public XmlAttribute CreateAttribute (string name)
                {
-                       return CreateAttribute (name, 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)
@@ -244,10 +270,11 @@ namespace System.Xml
                        return new XmlComment (data, this);
                }
 
-               [MonoTODO]
                protected internal virtual XmlAttribute CreateDefaultAttribute (string prefix, string localName, string namespaceURI)
                {
-                       throw new NotImplementedException ();
+                       XmlAttribute attr = CreateAttribute (prefix, localName, namespaceURI);
+                       attr.isDefault = true;
+                       return attr;
                }
 
                public virtual XmlDocumentFragment CreateDocumentFragment ()
@@ -261,6 +288,11 @@ namespace System.Xml
                        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);
@@ -285,7 +317,11 @@ 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);
+                       // FIXME: 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);
                }
 
@@ -294,10 +330,9 @@ namespace System.Xml
                        return new XmlEntityReference (name, this);
                }
 
-               [MonoTODO]
-               internal protected virtual XPathNavigator CreateNavigator (XmlNode node)
+               protected internal virtual XPathNavigator CreateNavigator (XmlNode node)
                {
-                       throw new NotImplementedException ();
+                       return new XmlDocumentNavigator (node);
                }
 
                public virtual XmlNode CreateNode (
@@ -332,7 +367,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);
@@ -390,9 +425,14 @@ namespace System.Xml
                }
 
                [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.
                public virtual XmlElement GetElementById (string elementId)
                {
-                       throw new NotImplementedException ();
+                       XmlAttribute attr = GetIdenticalAttribute (elementId);
+                       return attr != null ? attr.OwnerElement : null;
                }
 
                public virtual XmlNodeList GetElementsByTagName (string name)
@@ -453,118 +493,109 @@ namespace System.Xml
                        }
                }
 
-               [MonoTODO("default attributes (of imported doc); Entity; Notation")]
-               public virtual XmlNode ImportNode (XmlNode node, bool deep)
+               internal XmlAttribute GetIdenticalAttribute (string id)
                {
-                       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);
+                       XmlAttribute attr = this.idTable [id] as XmlAttribute;
+                       if (attr == null)
+                               return null;
+                       if (attr.OwnerElement == null || !attr.OwnerElement.IsRooted) {
+//                             idTable.Remove (id);
+                               return null;
+                       }
+                       return attr;
+               }
 
-                               default:
-                                       throw new NotImplementedException ();
+               public virtual XmlNode ImportNode (XmlNode node, bool deep)
+               {
+                       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));
+                               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)
+                                       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(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.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)
                {
-                       XmlReader xmlReader = new XmlTextReader (new XmlInputStream (inStream));
-                       Load (xmlReader);
+                       Load (new XmlTextReader (inStream));
                }
 
                public virtual void Load (string filename)
                {
-                       Load (new XmlTextReader (filename));
+                       XmlTextReader xr = new XmlTextReader (filename);
+                       xr.XmlResolver = resolver;
+                       Load (xr);
+                       xr.Close ();
                }
 
                public virtual void Load (TextReader txtReader)
                {
-                       Load (new XmlTextReader (txtReader));
+                       XmlTextReader xr = new XmlTextReader (txtReader);
+                       xr.XmlResolver = resolver;
+                       Load (xr);
                }
 
                public virtual void Load (XmlReader xmlReader)
@@ -575,6 +606,7 @@ namespace System.Xml
                        // like properties we have, etc.
                        RemoveAll ();
 
+                       this.baseURI = xmlReader.BaseURI;
                        // create all contents with use of ReadNode()
                        do {
                                XmlNode n = ReadNode (xmlReader);
@@ -585,7 +617,9 @@ namespace System.Xml
 
                public virtual void LoadXml (string xml)
                {
-                       XmlReader xmlReader = new XmlTextReader (new StringReader (xml));
+                       XmlTextReader xmlReader = new XmlTextReader (
+                               xml, XmlNodeType.Document, null);
+                       xmlReader.XmlResolver = resolver;
                        Load (xmlReader);
                }
 
@@ -650,23 +684,24 @@ 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)
                {
                        if(reader.NodeType == XmlNodeType.Element)
                                reader.MoveToFirstAttribute ();
                        else if(reader.NodeType != XmlNodeType.Attribute)
-                               throw new InvalidOperationException ("bad position to read attribute.");
+                               throw new InvalidOperationException (MakeReaderErrorMessage ("bad position to read attribute.", reader));
                        XmlAttribute attribute = CreateAttribute (reader.Prefix, reader.LocalName, reader.NamespaceURI);
                        ReadAttributeNodeValue (reader, attribute);
+
+                       // Keep the current reader position
+                       bool res;
+                       if (attribute.NamespaceURI == string.Empty || attribute.NamespaceURI == null)
+                               res = reader.MoveToAttribute (attribute.Name);
+                       else 
+                               res = reader.MoveToAttribute (attribute.LocalName, attribute.NamespaceURI);
+                       if (reader.IsDefault)
+                               attribute.SetDefault ();
                        return attribute;
                }
 
@@ -679,32 +714,34 @@ namespace System.Xml
                                        attribute.AppendChild (CreateEntityReference (reader.Name));
                                // FIXME: else if(NodeType == EndEntity) -- reset BaseURI and so on -- ;
                                else
-                                       // (IMHO) Children of Attribute is likely restricted to Text and EntityReference.
+                                       // Children of Attribute is restricted to CharacterData and EntityReference (Comment is not allowed).
                                        attribute.AppendChild (CreateTextNode (reader.Value));
                        }
                }
 
-               [MonoTODO("DTD parser is not completed.")]
-               public virtual XmlNode ReadNode(XmlReader reader)
+               public virtual XmlNode ReadNode (XmlReader reader)
                {
-                       // This logic was formerly defined in 'XmlNode.ConstructDOM()'
-
                        XmlNode resultNode = null;
                        XmlNode newNode = null;
                        XmlNode currentNode = null;
 
-                       if (reader.ReadState == ReadState.Initial)
+                       switch (reader.ReadState) {
+                       case ReadState.Interactive:
+                               break;
+                       case ReadState.Initial:
                                reader.Read ();
+                               break;
+                       default:
+                               return null;
+                       }
 
-                       // It was originally XmlDocument.Load(reader reader) when mcs was v0.16.
                        int startDepth = reader.Depth;
-//                     bool atStart = true;
                        bool ignoredWhitespace;
                        bool reachedEOF = false;
 
                        do {
                                ignoredWhitespace = false;
-                               if (reader.NodeType == XmlNodeType.None)
+                               if (reader.ReadState != ReadState.Interactive)
                                        if (reachedEOF)
                                                throw new Exception ("XML Reader reached to end while reading node.");
                                        else
@@ -748,8 +785,10 @@ namespace System.Xml
                                        break;
 
                                case XmlNodeType.EndElement:
-                                       if(currentNode == null || currentNode.Name != reader.Name)
-                                               throw new XmlException ("mismatch end tag.");
+                                       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;
 
@@ -773,24 +812,32 @@ namespace System.Xml
                                        newNode = CreateXmlDeclaration ("1.0" , String.Empty, String.Empty);
                                        ((XmlDeclaration)newNode).Value = reader.Value;
                                        if(currentNode != null)
-                                               throw new XmlException ("XmlDeclaration at invalid position.");
+                                               throw new XmlException (reader as IXmlLineInfo, "XmlDeclaration at invalid position.");
                                        break;
 
                                case XmlNodeType.DocumentType:
-                                       // This logic is kinda hack;-)
-                                       XmlTextReader xtReader = reader as XmlTextReader;
-                                       if(xtReader == null) {
-                                               xtReader = new XmlTextReader (reader.ReadOuterXml (),
-                                                       XmlNodeType.DocumentType,
-                                                       new XmlParserContext (NameTable, ConstructNamespaceManager(), XmlLang, XmlSpace));
-                                               xtReader.Read ();
-                                       }
-                                       newNode = CreateDocumentType (xtReader.Name,
-                                               xtReader.GetAttribute ("PUBLIC"),
-                                               xtReader.GetAttribute ("SYSTEM"),
-                                               xtReader.Value);
                                        if(currentNode != null)
-                                               throw new XmlException ("XmlDocumentType at invalid position.");
+                                               throw new XmlException (reader as IXmlLineInfo, "XmlDocumentType at invalid position.");
+
+                                       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;
+
+                                       if (dtd != null)
+                                               newNode = CreateDocumentType (dtd);
+                                       else
+                                               newNode = CreateDocumentType (reader.Name, reader ["PUBLIC"], reader ["SYSTEM"], reader.Value);
+
                                        break;
 
                                case XmlNodeType.EntityReference:
@@ -815,29 +862,46 @@ namespace System.Xml
                                                ignoredWhitespace = true;
                                        break;
                                }
-                               reader.Read ();
+                               // 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;
                }
 
+               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);
+                       else
+                               return message;
+               }
+
+               internal void RemoveIdenticalAttribute (string id)
+               {
+                       idTable.Remove (id);
+               }
+
                public virtual void Save(Stream outStream)
                {
-                       XmlTextWriter xmlWriter = new XmlTextWriter (outStream, Encoding.UTF8);
+                       XmlTextWriter xmlWriter = new XmlTextWriter (outStream, TextEncoding);
                        xmlWriter.Formatting = Formatting.Indented;
                        WriteContentTo (xmlWriter);
-                       xmlWriter.Close ();
+                       xmlWriter.Flush ();
                }
 
                public virtual void Save (string filename)
                {
-                       XmlTextWriter xmlWriter = new XmlTextWriter (filename, Encoding.UTF8);
+                       XmlTextWriter xmlWriter = new XmlTextWriter (filename, TextEncoding);
                        xmlWriter.Formatting = Formatting.Indented;
                        WriteContentTo (xmlWriter);
                        xmlWriter.Close ();
                }
 
-               [MonoTODO]
                public virtual void Save (TextWriter writer)
                {
                        XmlTextWriter xmlWriter = new XmlTextWriter (writer);
@@ -851,7 +915,12 @@ 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 ();
                }