2003-01-21 Atsushi Enomoto <ginga@kit.hi-ho.ne.jp>
[mono.git] / mcs / class / System.XML / System.Xml / XmlDocument.cs
index 8db78cb53a7791708afc9f4ff03a9f1f9bb1a8a2..e54a1ed4dcc9111d7104a74683a9c7453010063a 100644 (file)
@@ -7,9 +7,11 @@
 //   Jason Diamond <jason@injektilo.org>
 //   Miguel de Icaza (miguel@ximian.com)
 //   Duncan Mak (duncan@ximian.com)
+//   Atsushi Enomoto (ginga@kit.hi-ho.ne.jp)
 //
 // (C) 2001 Daniel Weber
-// (C) 2002 Kral Ferch, Jason Diamond, Miguel de Icaza, Duncan Mak
+// (C) 2002 Kral Ferch, Jason Diamond, Miguel de Icaza, Duncan Mak,
+//   Atsushi Enomoto
 //
 
 using System;
@@ -29,33 +31,31 @@ namespace System.Xml
                XmlNameTable nameTable;
                string baseURI = String.Empty;
                XmlImplementation implementation;
+               bool preserveWhitespace = false;
+               WeakReference reusableXmlTextReader;
 
                #endregion
 
                #region Constructors
 
-               public XmlDocument () : base (null)
+               public XmlDocument () : this (null, null)
                {
-                       implementation = new XmlImplementation();
-                       nameTable = implementation.internalNameTable;
-                       AddDefaultNameTableKeys();
                }
 
-               protected internal XmlDocument (XmlImplementation imp) : base (null)
+               protected internal XmlDocument (XmlImplementation imp) : this (imp, null)
                {
-                       implementation = imp;
-                       nameTable = imp.internalNameTable;
-                       AddDefaultNameTableKeys();
                }
 
-               public XmlDocument (XmlNameTable nt) : base (null)
+               public XmlDocument (XmlNameTable nt) : this (null, nt)
                {
-                       implementation = new XmlImplementation();
-                       implementation.internalNameTable = nt;
-                       nameTable = nt;
-                       AddDefaultNameTableKeys();
                }
 
+               XmlDocument (XmlImplementation impl, XmlNameTable nt) : base (null)
+               {
+                       implementation = (impl != null) ? impl : new XmlImplementation ();
+                       nameTable = (nt != null) ? nt : implementation.internalNameTable;
+                       AddDefaultNameTableKeys ();
+               }
                #endregion
 
                #region Events
@@ -82,6 +82,19 @@ 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;
@@ -111,14 +124,13 @@ namespace System.Xml
                        get { return implementation; }
                }
 
-               [MonoTODO ("Setter.")]
                public override string InnerXml {
                        get {
-                               // Not sure why this is an override.  Passing through for now.
-                               // ... Maybe its setter may be an override :-) [ginga]
                                return base.InnerXml;
                        }
-                       set { throw new NotImplementedException(); }
+                       set {   // reason for overriding
+                               this.LoadXml (value);
+                       }
                }
 
                public override bool IsReadOnly {
@@ -161,25 +173,41 @@ namespace System.Xml
                        get { return null; }
                }
 
-               [MonoTODO]
                public bool PreserveWhitespace {
-                       get { throw new NotImplementedException(); }
-                       set { throw new NotImplementedException(); }
+                       get { return preserveWhitespace; }
+                       set { preserveWhitespace = value; }
+               }
+
+               internal override string XmlLang {
+                       get { return String.Empty; }
                }
 
                [MonoTODO]
                public virtual XmlResolver XmlResolver {
-                       set { throw new NotImplementedException(); }
+                       set { throw new NotImplementedException (); }
+               }
+
+               internal override XmlSpace XmlSpace {
+                       get {
+                               return XmlSpace.None;
+                       }
                }
 
                #endregion
 
                #region Methods
 
-               [MonoTODO]
+               [MonoTODO("Should BaseURI be cloned?")]
                public override XmlNode CloneNode (bool deep)
                {
-                       throw new NotImplementedException ();
+                       XmlDocument doc = implementation.CreateDocument ();
+                       doc.PreserveWhitespace = PreserveWhitespace;    // required?
+                       if(deep)
+                       {
+                               foreach(XmlNode n in ChildNodes)
+                                       doc.AppendChild (doc.ImportNode (n, deep));
+                       }
+                       return doc;
                }
 
                public XmlAttribute CreateAttribute (string name)
@@ -212,7 +240,7 @@ namespace System.Xml
 
                public virtual XmlComment CreateComment (string data)
                {
-                       return new XmlComment(data, this);
+                       return new XmlComment (data, this);
                }
 
                [MonoTODO]
@@ -223,7 +251,7 @@ namespace System.Xml
 
                public virtual XmlDocumentFragment CreateDocumentFragment ()
                {
-                       return new XmlDocumentFragment(this);
+                       return new XmlDocumentFragment (this);
                }
 
                public virtual XmlDocumentType CreateDocumentType (string name, string publicId,
@@ -245,7 +273,7 @@ namespace System.Xml
                        string localName;
 
                        ParseName (qualifiedName, out prefix, out localName);
-
+                       
                        return CreateElement (prefix, localName, namespaceURI);
                }
 
@@ -256,18 +284,17 @@ 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);
                }
 
-               [MonoTODO]
                public virtual XmlEntityReference CreateEntityReference (string name)
                {
-                       throw new NotImplementedException ();
+                       return new XmlEntityReference (name, this);
                }
 
                [MonoTODO]
-               protected internal virtual XPathNavigator CreateNavigator (XmlNode node)
+               internal protected virtual XPathNavigator CreateNavigator (XmlNode node)
                {
                        throw new NotImplementedException ();
                }
@@ -425,7 +452,7 @@ namespace System.Xml
                        }
                }
 
-               [MonoTODO("default attributes (of imported doc); EntityReferences; Entity; Notation")]
+               [MonoTODO("default attributes (of imported doc); Entity; Notation")]
                public virtual XmlNode ImportNode (XmlNode node, bool deep)
                {
                        switch(node.NodeType)
@@ -433,44 +460,44 @@ namespace System.Xml
                                case XmlNodeType.Attribute:
                                        {
                                                XmlAttribute src_att = node as XmlAttribute;
-                                               XmlAttribute dst_att = this.CreateAttribute(src_att.Prefix, src_att.LocalName, src_att.NamespaceURI);
+                                               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);
+                                       return this.CreateCDataSection (node.Value);
 
                                case XmlNodeType.Comment:
-                                       return this.CreateComment(node.Value);
+                                       return this.CreateComment (node.Value);
 
                                case XmlNodeType.Document:
-                                       throw new XmlException("Document cannot be imported.");
+                                       throw new XmlException ("Document cannot be imported.");
 
                                case XmlNodeType.DocumentFragment:
                                        {
-                                               XmlDocumentFragment df = this.CreateDocumentFragment();
+                                               XmlDocumentFragment df = this.CreateDocumentFragment ();
                                                if(deep)
                                                {
                                                        foreach(XmlNode n in node.ChildNodes)
                                                        {
-                                                               df.AppendChild(this.ImportNode(n, deep));
+                                                               df.AppendChild (this.ImportNode (n, deep));
                                                        }
                                                }
                                                return df;
                                        }
 
                                case XmlNodeType.DocumentType:
-                                       throw new XmlException("DocumentType cannot be imported.");
+                                       throw new XmlException ("DocumentType cannot be imported.");
 
                                case XmlNodeType.Element:
                                        {
                                                XmlElement src = (XmlElement)node;
-                                               XmlElement dst = this.CreateElement(src.Prefix, src.LocalName, src.NamespaceURI);
+                                               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));
+                                                               dst.SetAttributeNode ((XmlAttribute)this.ImportNode (attr, deep));
                                                        if(DocumentType != null)
                                                        {
                                                                // TODO: create default attribute values
@@ -479,7 +506,7 @@ namespace System.Xml
                                                if(deep)
                                                {
                                                        foreach(XmlNode n in src.ChildNodes)
-                                                               dst.AppendChild(this.ImportNode(n, deep));
+                                                               dst.AppendChild (this.ImportNode (n, deep));
                                                }
                                                return dst;
                                        }
@@ -492,10 +519,8 @@ namespace System.Xml
                                case XmlNodeType.Entity:
                                        throw new NotImplementedException ();   // TODO
 
-                               // [2002.10.14] CreateEntityReference not implemented.
                                case XmlNodeType.EntityReference:
-                                       throw new NotImplementedException("ImportNode of EntityReference not implemented mainly because CreateEntityReference was implemented in the meantime.");
-//                                     return this.CreateEntityReference(node.Name);
+                                       return this.CreateEntityReference (node.Name);
 
                                case XmlNodeType.None:
                                        throw new XmlException ("Illegal ImportNode call for NodeType.None");
@@ -505,20 +530,20 @@ namespace System.Xml
 
                                case XmlNodeType.ProcessingInstruction:
                                        XmlProcessingInstruction pi = node as XmlProcessingInstruction;
-                                       return this.CreateProcessingInstruction(pi.Target, pi.Data);
+                                       return this.CreateProcessingInstruction (pi.Target, pi.Data);
 
                                case XmlNodeType.SignificantWhitespace:
-                                       return this.CreateSignificantWhitespace(node.Value);
+                                       return this.CreateSignificantWhitespace (node.Value);
 
                                case XmlNodeType.Text:
-                                       return this.CreateTextNode(node.Value);
+                                       return this.CreateTextNode (node.Value);
 
                                case XmlNodeType.Whitespace:
-                                       return this.CreateWhitespace(node.Value);
+                                       return this.CreateWhitespace (node.Value);
 
                                case XmlNodeType.XmlDeclaration:
                                        XmlDeclaration srcDecl = node as XmlDeclaration;
-                                       return this.CreateXmlDeclaration(srcDecl.Version, srcDecl.Encoding, srcDecl.Standalone);
+                                       return this.CreateXmlDeclaration (srcDecl.Version, srcDecl.Encoding, srcDecl.Standalone);
 
                                default:
                                        throw new NotImplementedException ();
@@ -551,11 +576,12 @@ namespace System.Xml
                        // like properties we have, etc.
                        RemoveAll ();
 
-                       XmlNode currentNode = this;
-
-                       // This method of XmlNode is previously written here.
-                       // Then I(ginga) moved them to use this logic with XmlElement.
-                       this.ConstructDOM(xmlReader, currentNode);
+                       // create all contents with use of ReadNode()
+                       do {
+                               XmlNode n = ReadNode (xmlReader);
+                               if(n == null) break;
+                               AppendChild (n);
+                       } while (true);
                }
 
                public virtual void LoadXml (string xml)
@@ -625,26 +651,189 @@ namespace System.Xml
                        }
                }
 
-               [MonoTODO]
+               // 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.");
+                       XmlAttribute attribute = CreateAttribute (reader.Prefix, reader.LocalName, reader.NamespaceURI);
+                       ReadAttributeNodeValue (reader, attribute);
+                       return attribute;
+               }
+
+               // Reads attribute from XmlReader and then creates attribute value children. XmlAttribute also uses this.
+               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.
+                                       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.
+                                       attribute.AppendChild (CreateTextNode (reader.Value));
+                       }
+               }
+
+               [MonoTODO("DTD parser is not completed.")]
                public virtual XmlNode ReadNode(XmlReader reader)
                {
-                       throw new NotImplementedException ();
+                       // This logic was formerly defined in 'XmlNode.ConstructDOM()'
+
+                       XmlNode resultNode = null;
+                       XmlNode newNode = null;
+                       XmlNode currentNode = null;
+                       // It was originally XmlDocument.Load(reader reader) when mcs was v0.16.
+                       int startDepth = reader.Depth;
+                       bool atStart = true;
+                       bool ignoredWhitespace;
+
+                       do {
+                               ignoredWhitespace = false;
+                               reader.Read ();
+                               // This complicated check is because we shouldn't make
+                               // improper additional XmlReader.Read() by this method itself.
+                               if(atStart && (reader.NodeType == XmlNodeType.EndElement || 
+                                       reader.NodeType == XmlNodeType.EndEntity))
+                                       throw new InvalidOperationException ("the XmlReader now holds invalid position.");
+                               atStart = false;
+                               switch (reader.NodeType) {
+
+                               case XmlNodeType.Attribute:
+                                       newNode = ReadAttributeNode (reader);
+                                       break;
+
+                               case XmlNodeType.CDATA:
+                                       newNode = CreateCDataSection (reader.Value);
+                                       if(currentNode != null)
+                                               currentNode.AppendChild (newNode);
+                                       break;
+
+                               case XmlNodeType.Comment:
+                                       newNode = CreateComment (reader.Value);
+                                       if(currentNode != null)
+                                               currentNode.AppendChild (newNode);
+                                       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;
+
+                                       // set the element's attributes.
+                                       while (reader.MoveToNextAttribute ()) {
+                                               element.SetAttributeNode (ReadAttributeNode (reader));
+                                       }
+
+                                       reader.MoveToElement ();
+
+                                       if (!reader.IsEmptyElement)
+                                               currentNode = element;
+
+                                       break;
+
+                               case XmlNodeType.EndElement:
+                                       if(currentNode.Name != reader.Name)
+                                               throw new XmlException ("mismatch end tag.");
+                                       currentNode = currentNode.ParentNode;
+                                       break;
+
+                               case XmlNodeType.EndEntity:
+                                       break;  // no operation
+
+                               case XmlNodeType.ProcessingInstruction:
+                                       newNode = CreateProcessingInstruction (reader.Name, reader.Value);
+                                       if(currentNode != null)
+                                               currentNode.AppendChild (newNode);
+                                       break;
+
+                               case XmlNodeType.Text:
+                                       newNode = CreateTextNode (reader.Value);
+                                       if(currentNode != null)
+                                               currentNode.AppendChild (newNode);
+                                       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 ("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.");
+                                       break;
+
+                               case XmlNodeType.EntityReference:
+                                       newNode = CreateEntityReference (reader.Name);
+                                       if(currentNode != null)
+                                               currentNode.AppendChild (newNode);
+                                       break;
+
+                               case XmlNodeType.SignificantWhitespace:
+                                       newNode = CreateSignificantWhitespace (reader.Value);
+                                       if(currentNode != null)
+                                               currentNode.AppendChild (newNode);
+                                       break;
+
+                               case XmlNodeType.Whitespace:
+                                       if(PreserveWhitespace) {
+                                               newNode = CreateWhitespace (reader.Value);
+                                               if(currentNode != null)
+                                                       currentNode.AppendChild (newNode);
+                                       }
+                                       else
+                                               ignoredWhitespace = true;
+                                       break;
+                               }
+                       } while(ignoredWhitespace ||
+                               reader.Depth > startDepth || 
+                               // This complicated condition is because reader.Depth was set
+                               // before XmlTextReader.depth increments ;-)
+                               (reader.Depth == startDepth && reader.NodeType == XmlNodeType.Element && reader.IsEmptyElement == false)
+                               );
+                       return resultNode != null ? resultNode : newNode;
                }
 
-               [MonoTODO ("Verify what encoding is used by default;  Should use PreserveWhiteSpace")]
                public virtual void Save(Stream outStream)
                {
-                       // To implementor: utf-8 is OK, at least for (ginga's) Japanese environment.
                        XmlTextWriter xmlWriter = new XmlTextWriter (outStream, Encoding.UTF8);
+                       xmlWriter.Formatting = Formatting.Indented;
                        WriteContentTo (xmlWriter);
                        xmlWriter.Close ();
                }
 
-               [MonoTODO ("Verify what encoding is used by default; Should use PreseveWhiteSpace")]
                public virtual void Save (string filename)
                {
-                       // To implementor: utf-8 is OK, at least for (ginga's) Japanese environment.
                        XmlTextWriter xmlWriter = new XmlTextWriter (filename, Encoding.UTF8);
+                       xmlWriter.Formatting = Formatting.Indented;
                        WriteContentTo (xmlWriter);
                        xmlWriter.Close ();
                }
@@ -653,11 +842,11 @@ namespace System.Xml
                public virtual void Save (TextWriter writer)
                {
                        XmlTextWriter xmlWriter = new XmlTextWriter (writer);
+                       xmlWriter.Formatting = Formatting.Indented;
                        WriteContentTo (xmlWriter);
                        xmlWriter.Flush ();
                }
 
-               [MonoTODO ("Should preserve white space if PreserveWhisspace is set")]
                public virtual void Save (XmlWriter xmlWriter)
                {
                        //
@@ -669,32 +858,33 @@ namespace System.Xml
 
                public override void WriteContentTo (XmlWriter w)
                {
-                       foreach(XmlNode childNode in ChildNodes)
-                               childNode.WriteTo(w);
+                       foreach(XmlNode childNode in ChildNodes) {
+                               childNode.WriteTo (w);
+                       }
                }
 
                public override void WriteTo (XmlWriter w)
                {
-                       WriteContentTo(w);
+                       WriteContentTo (w);
                }
 
-               private void AddDefaultNameTableKeys()
+               private void AddDefaultNameTableKeys ()
                {
                        // The following keys are default of MS .NET Framework
-                       nameTable.Add("#text");
-                       nameTable.Add("xml");
-                       nameTable.Add("xmlns");
-                       nameTable.Add("#entity");
-                       nameTable.Add("#document-fragment");
-                       nameTable.Add("#comment");
-                       nameTable.Add("space");
-                       nameTable.Add("id");
-                       nameTable.Add("#whitespace");
-                       nameTable.Add("http://www.w3.org/2000/xmlns/");
-                       nameTable.Add("#cdata-section");
-                       nameTable.Add("lang");
-                       nameTable.Add("#document");
-                       nameTable.Add("#significant-whitespace");
+                       nameTable.Add ("#text");
+                       nameTable.Add ("xml");
+                       nameTable.Add ("xmlns");
+                       nameTable.Add ("#entity");
+                       nameTable.Add ("#document-fragment");
+                       nameTable.Add ("#comment");
+                       nameTable.Add ("space");
+                       nameTable.Add ("id");
+                       nameTable.Add ("#whitespace");
+                       nameTable.Add ("http://www.w3.org/2000/xmlns/");
+                       nameTable.Add ("#cdata-section");
+                       nameTable.Add ("lang");
+                       nameTable.Add ("#document");
+                       nameTable.Add ("#significant-whitespace");
                }
                #endregion
        }