2003-03-15 Atsushi Enomoto <ginga@kit.hi-ho.ne.jp>
[mono.git] / mcs / class / System.XML / System.Xml / XmlTextWriter.cs
index 351c4670923ae33c7dcd92e6e4a0c5f34e12eecf..eb0cf3b1ca4e44293e6f1275616d7d7580f582b9 100644 (file)
@@ -6,6 +6,9 @@
 //
 // (C) 2002 Kral Ferch
 //
+// [FIXME]
+// Document state should be considered.
+//
 
 using System;
 using System.Collections;
@@ -18,28 +21,33 @@ namespace System.Xml
        {
                #region Fields
 
-               protected TextWriter w;
-               protected bool nullEncoding = false;
-               protected bool openWriter = true;
-               protected bool openStartElement = false;
-               protected bool openStartAttribute = false;
-               protected bool documentStarted = false;
-               private bool namespaces = true;
-               protected bool openAttribute = false;
-               protected bool attributeWrittenForElement = false;
-               protected Stack openElements = new Stack ();
-               private Formatting formatting = Formatting.None;
-               private int indentation = 2;
-               private char indentChar = ' ';
-               protected string indentChars = "  ";
-               private char quoteChar = '\"';
-               protected int indentLevel = 0;
-               protected string indentFormatting;
-               protected Stream baseStream = null;
-               protected string xmlLang = null;
-               protected XmlSpace xmlSpace = XmlSpace.None;
-               protected bool openXmlLang = false;
-               protected bool openXmlSpace = false;
+               TextWriter w;
+               bool nullEncoding = false;
+               bool openWriter = true;
+               bool openStartElement = false;
+               bool openStartAttribute = false;
+               bool documentStarted = false;
+               bool namespaces = true;
+               bool openAttribute = false;
+               bool attributeWrittenForElement = false;
+               Stack openElements = new Stack ();
+               Formatting formatting = Formatting.None;
+               int indentation = 2;
+               char indentChar = ' ';
+               string indentChars = "  ";
+               char quoteChar = '\"';
+               int indentLevel = 0;
+               string indentFormatting;
+               Stream baseStream = null;
+               string xmlLang = null;
+               XmlSpace xmlSpace = XmlSpace.None;
+               bool openXmlLang = false;
+               bool openXmlSpace = false;
+               string openElementPrefix;
+               string openElementNS;
+               bool hasRoot = false;
+               Hashtable writtenAttributes = new Hashtable ();
+               bool checkMultipleAttributes = false;
 
                #endregion
 
@@ -48,6 +56,7 @@ namespace System.Xml
                public XmlTextWriter (TextWriter w) : base ()
                {
                        this.w = w;
+                       nullEncoding = (w.Encoding == null);
                        
                        try {
                                baseStream = ((StreamWriter)w).BaseStream;
@@ -66,10 +75,9 @@ namespace System.Xml
                        baseStream = w;
                }
 
-               public XmlTextWriter (string filename, Encoding encoding) : base ()
+               public XmlTextWriter (string filename, Encoding encoding) :
+                       this (new FileStream (filename, FileMode.Create, FileAccess.Write, FileShare.None), encoding)
                {
-                       this.w = new StreamWriter(filename, false, encoding);
-                       baseStream = ((StreamWriter)w).BaseStream;
                }
 
                #endregion
@@ -86,7 +94,7 @@ namespace System.Xml
                        set { formatting = value; }
                }
 
-               public bool IndentingOverriden 
+               private bool IndentingOverriden 
                {
                        get {
                                if (openElements.Count == 0)
@@ -175,15 +183,58 @@ namespace System.Xml
                #endregion
 
                #region Methods
+               private void AddMissingElementXmlns ()
+               {
+                       // output namespace declaration if not exist.
+                       string prefix = openElementPrefix;
+                       string ns = openElementNS;
+                       openElementPrefix = null;
+                       openElementNS = null;
+
+                       // LAMESPEC: If prefix was already assigned another nsuri, then this element's nsuri goes away!
+
+                       if (ns != null) 
+                       {
+                               string formatXmlns = String.Empty;
+                               if (ns != String.Empty)
+                               {
+                                       string existingPrefix = namespaceManager.LookupPrefix (ns);
+                                       bool addDefaultNamespace = false;
+
+                                       if (existingPrefix == null) 
+                                       {
+                                               namespaceManager.AddNamespace (prefix, ns);
+                                               addDefaultNamespace = true;
+                                       }
+
+                                       if (prefix == String.Empty)
+                                               prefix = existingPrefix;
+
+                                       if (prefix != existingPrefix)
+                                               formatXmlns = String.Format (" xmlns:{0}={1}{2}{1}", prefix, quoteChar, ns);
+                                       else if (addDefaultNamespace)
+                                               formatXmlns = String.Format (" xmlns={0}{1}{0}", quoteChar, ns);
+                               } 
+                               else if ((prefix == String.Empty) && (namespaceManager.LookupNamespace (prefix) != ns)) 
+                               {
+                                       namespaceManager.AddNamespace (prefix, ns);
+                                       formatXmlns = String.Format (" xmlns={0}{0}", quoteChar);
+                               }
+                               if(formatXmlns != String.Empty) {
+                                       string xmlns = formatXmlns.Trim ();
+                                       if (checkMultipleAttributes && !writtenAttributes.Contains (xmlns.Substring (0, xmlns.IndexOf ('='))))
+                                               w.Write(formatXmlns);
+                               }
+                       }
+               }
 
                private void CheckState ()
                {
                        if (!openWriter) {
                                throw new InvalidOperationException ("The Writer is closed.");
                        }
-
                        if ((documentStarted == true) && (formatting == Formatting.Indented) && (!IndentingOverriden)) {
-                               indentFormatting = "\r\n";
+                               indentFormatting = w.NewLine;
                                if (indentLevel > 0) {
                                        for (int i = 0; i < indentLevel; i++)
                                                indentFormatting += indentChars;
@@ -197,26 +248,38 @@ namespace System.Xml
 
                public override void Close ()
                {
-                       while (openElements.Count > 0) {
-                               WriteEndElement();
-                       }
+                       CloseOpenAttributeAndElements ();
 
                        w.Close();
                        ws = WriteState.Closed;
                        openWriter = false;
                }
 
-               private void CloseStartElement ()
+               private void CloseOpenAttributeAndElements ()
                {
-                       if (openStartElement) 
-                       {
-                               w.Write(">");
-                               ws = WriteState.Content;
-                               openStartElement = false;
-                               attributeWrittenForElement = false;
+                       if (openAttribute)
+                               WriteEndAttribute ();
+
+                       while (openElements.Count > 0) {
+                               WriteEndElement();
                        }
                }
 
+               private void CloseStartElement ()
+               {
+                       if (!openStartElement)
+                               return;
+
+                       AddMissingElementXmlns ();
+
+                       w.Write (">");
+                       ws = WriteState.Content;
+                       openStartElement = false;
+                       attributeWrittenForElement = false;
+                       checkMultipleAttributes = false;
+                       writtenAttributes.Clear ();
+               }
+
                public override void Flush ()
                {
                        w.Flush ();
@@ -226,9 +289,10 @@ namespace System.Xml
                {
                        string prefix = namespaceManager.LookupPrefix (ns);
 
-                       if (prefix == String.Empty)
-                               prefix = null;
-
+                       // XmlNamespaceManager has changed to return null when NSURI not found.
+                       // (Contradiction to the documentation.)
+                       //if (prefix == String.Empty)
+                       //      prefix = null;
                        return prefix;
                }
 
@@ -291,10 +355,23 @@ namespace System.Xml
                        w.Write ("<!--{0}-->", text);
                }
 
-               [MonoTODO]
                public override void WriteDocType (string name, string pubid, string sysid, string subset)
                {
-                       throw new NotImplementedException ();
+                       if (name == null || name.Trim ().Length == 0)
+                               throw new ArgumentException ("Invalid DOCTYPE name", "name");
+
+                       w.Write ("<!DOCTYPE ");
+                       w.Write (name);
+                       if (pubid != null) {
+                               w.Write (String.Format (" PUBLIC {0}{1}{0} {0}{2}{0}", quoteChar, pubid, sysid));
+                       } else if (sysid != null) {
+                               w.Write (String.Format (" SYSTEM {0}{1}{0}", quoteChar, sysid));
+                       }
+
+                       if (subset != null)
+                               w.Write ("[" + subset + "]");
+
+                       w.Write('>');
                }
 
                public override void WriteEndAttribute ()
@@ -322,27 +399,42 @@ namespace System.Xml
                        openAttribute = false;
                }
 
-               [MonoTODO]
                public override void WriteEndDocument ()
                {
-                       throw new NotImplementedException ();
+                       CloseOpenAttributeAndElements ();
+
+                       if (!hasRoot)
+                               throw new ArgumentException ("This document does not have a root element.");
+
+                       ws = WriteState.Start;
+                       hasRoot = false;
                }
 
                public override void WriteEndElement ()
+               {
+                       WriteEndElementInternal (false);
+               }
+
+               private void WriteEndElementInternal (bool fullEndElement)
                {
                        if (openElements.Count == 0)
                                throw new InvalidOperationException("There was no XML start tag open.");
 
                        indentLevel--;
-
                        CheckState ();
+                       AddMissingElementXmlns ();
 
                        if (openStartElement) {
-                               w.Write (" />");
+                               if (openAttribute)
+                                       WriteEndAttribute ();
+                               if (fullEndElement)
+                                       w.Write ("></{0}>", ((XmlTextWriterOpenElement)openElements.Peek ()).Name);
+                               else
+                                       w.Write (" />");
+
                                openElements.Pop ();
                                openStartElement = false;
-                       }
-                       else {
+                       } else {
                                w.Write ("{0}</{1}>", indentFormatting, openElements.Pop ());
                        }
 
@@ -355,22 +447,30 @@ namespace System.Xml
                        throw new NotImplementedException ();
                }
 
-               [MonoTODO]
                public override void WriteFullEndElement ()
                {
-                       throw new NotImplementedException ();
+                       WriteEndElementInternal (true);
+               }
+
+               private void CheckValidChars (string name, bool firstOnlyLetter)
+               {
+                       foreach (char c in name) {
+                               if (XmlConvert.IsInvalid (c, firstOnlyLetter))
+                                       throw new ArgumentException ("There is an invalid character: '" + c +
+                                                                    "'", "name");
+                       }
                }
 
-               [MonoTODO]
                public override void WriteName (string name)
                {
-                       throw new NotImplementedException ();
+                       CheckValidChars (name, true);
+                       w.Write (name);
                }
 
-               [MonoTODO]
                public override void WriteNmToken (string name)
                {
-                       throw new NotImplementedException ();
+                       CheckValidChars (name, false);
+                       w.Write (name);
                }
 
                public override void WriteProcessingInstruction (string name, string text)
@@ -388,19 +488,21 @@ namespace System.Xml
                [MonoTODO]
                public override void WriteQualifiedName (string localName, string ns)
                {
-                       throw new NotImplementedException ();
+                       if (localName == null || localName == String.Empty)
+                               throw new ArgumentException ();
+
+                       CheckState ();
+                       w.Write ("{0}:{1}", ns, localName);
                }
 
-               [MonoTODO]
                public override void WriteRaw (string data)
                {
-                       throw new NotImplementedException ();
+                       WriteStringInternal (data, false);
                }
 
-               [MonoTODO]
                public override void WriteRaw (char[] buffer, int index, int count)
                {
-                       throw new NotImplementedException ();
+                       WriteStringInternal (new string (buffer, index, count), false);
                }
 
                public override void WriteStartAttribute (string prefix, string localName, string ns)
@@ -411,8 +513,8 @@ namespace System.Xml
                        if ((prefix == "xml") && (localName == "space"))
                                openXmlSpace = true;
 
-                       if ((prefix == "xmlns") && (localName == "xmlns"))
-                               throw new ArgumentException ("Prefixes beginning with \"xml\" (regardless of whether the characters are uppercase, lowercase, or some combination thereof) are reserved for use by XML.");
+                       if ((prefix == "xmlns") && (localName.ToLower ().StartsWith ("xml")))
+                               throw new ArgumentException ("Prefixes beginning with \"xml\" (regardless of whether the characters are uppercase, lowercase, or some combination thereof) are reserved for use by XML: " + prefix + ":" + localName);
 
                        CheckState ();
 
@@ -433,7 +535,8 @@ namespace System.Xml
                                string existingPrefix = namespaceManager.LookupPrefix (ns);
 
                                if (prefix == String.Empty)
-                                       prefix = existingPrefix;
+                                       prefix = (existingPrefix == null) ?
+                                               String.Empty : existingPrefix;
                        }
 
                        if (prefix != String.Empty) 
@@ -444,11 +547,25 @@ namespace System.Xml
                        if (openStartElement || attributeWrittenForElement)
                                formatSpace = " ";
 
+                       // If already written, then break up.
+                       if (checkMultipleAttributes &&
+                               writtenAttributes.Contains (formatPrefix + localName))
+                               return;
+
                        w.Write ("{0}{1}{2}={3}", formatSpace, formatPrefix, localName, quoteChar);
+                       if (checkMultipleAttributes)
+                               writtenAttributes.Add (formatPrefix + localName, formatPrefix + localName);
 
                        openAttribute = true;
                        attributeWrittenForElement = true;
                        ws = WriteState.Attribute;
+                       if (prefix == String.Empty && localName == "xmlns") {
+                               if (namespaceManager.LookupNamespace (prefix) == null)
+                                       namespaceManager.AddNamespace (prefix, ns);
+                       } else if (prefix == "xmlns") {
+                               if (namespaceManager.LookupNamespace (localName) == null)
+                                       namespaceManager.AddNamespace (localName, ns);
+                       }
                }
 
                public override void WriteStartDocument ()
@@ -473,12 +590,17 @@ namespace System.Xml
                        if (documentStarted == true)
                                throw new InvalidOperationException("WriteStartDocument should be the first call.");
 
+                       if (hasRoot)
+                               throw new XmlException ("WriteStartDocument called twice.");
+
+                       hasRoot = true;
+
                        CheckState ();
 
                        string encodingFormatting = "";
 
-                       if (!nullEncoding)
-                               encodingFormatting = String.Format (" encoding={0}{1}{0}", quoteChar, w.Encoding.HeaderName);
+                       if (!nullEncoding) 
+                               encodingFormatting = String.Format (" encoding={0}{1}{0}", quoteChar, w.Encoding.WebName);
 
                        w.Write("<?xml version={0}1.0{0}{1}{2}?>", quoteChar, encodingFormatting, standaloneFormatting);
                        ws = WriteState.Prolog;
@@ -493,52 +615,37 @@ namespace System.Xml
                        WriteStartElementInternal (prefix, localName, ns);
                }
 
-               protected override void WriteStartElementInternal (string prefix, string localName, string ns)
+               private void WriteStartElementInternal (string prefix, string localName, string ns)
                {
-                       if (prefix == null)
-                               prefix = String.Empty;
-
-                       if (ns == null)
-                               ns = String.Empty;
-
-                       if ((prefix != String.Empty) && ((ns == null) || (ns == String.Empty)))
+                       if ((prefix != null && prefix != String.Empty) && ((ns == null) || (ns == String.Empty)))
                                throw new ArgumentException ("Cannot use a prefix with an empty namespace.");
 
                        CheckState ();
                        CloseStartElement ();
+                       writtenAttributes.Clear ();
+                       checkMultipleAttributes = true;
+                       
+                       if (prefix == null)
+                               prefix = namespaceManager.LookupPrefix (ns);
+                       if (prefix == null)
+                               prefix = String.Empty;
 
-                       string formatXmlns = "";
                        string formatPrefix = "";
 
-                       if (ns != String.Empty) 
-                       {
-                               string existingPrefix = namespaceManager.LookupPrefix (ns);
-
-                               if (prefix == String.Empty)
-                                       prefix = existingPrefix;
-
-                               if (prefix != existingPrefix)
-                                       formatXmlns = String.Format (" xmlns:{0}={1}{2}{1}", prefix, quoteChar, ns);
-                               else if (existingPrefix == String.Empty)
-                                       formatXmlns = String.Format (" xmlns={0}{1}{0}", quoteChar, ns);
-                       }
-                       else if ((prefix == String.Empty) && (namespaceManager.LookupNamespace(prefix) != String.Empty)) {
-                               formatXmlns = String.Format (" xmlns={0}{0}", quoteChar);
-                       }
-
-                       if (prefix != String.Empty) {
-                               formatPrefix = prefix + ":";
+                       if(ns != null) {
+                               if (prefix != String.Empty)
+                                       formatPrefix = prefix + ":";
                        }
 
-                       w.Write ("{0}<{1}{2}{3}", indentFormatting, formatPrefix, localName, formatXmlns);
+                       w.Write ("{0}<{1}{2}", indentFormatting, formatPrefix, localName);
 
                        openElements.Push (new XmlTextWriterOpenElement (formatPrefix + localName));
                        ws = WriteState.Element;
                        openStartElement = true;
+                       openElementNS = ns;
+                       openElementPrefix = prefix;
 
                        namespaceManager.PushScope ();
-                       namespaceManager.AddNamespace (prefix, ns);
-
                        indentLevel++;
                }
 
@@ -547,33 +654,48 @@ namespace System.Xml
                        if (ws == WriteState.Prolog)
                                throw new InvalidOperationException ("Token content in state Prolog would result in an invalid XML document.");
 
+                       WriteStringInternal (text, true);
+               }
+
+               private void WriteStringInternal (string text, bool entitize)
+               {
                        if (text == null)
                                text = String.Empty;
 
-                       if (text != String.Empty) {
+                       if (text != String.Empty) 
+                       {
                                CheckState ();
 
-                               text = text.Replace ("&", "&amp;");
-                               text = text.Replace ("<", "&lt;");
-                               text = text.Replace (">", "&gt;");
-                               
-                               if (openAttribute) {
-                                       if (quoteChar == '"')
-                                               text = text.Replace ("\"", "&quot;");
-                                       else
-                                               text = text.Replace ("'", "&apos;");
+                               if (entitize)
+                               {
+                                       text = text.Replace ("&", "&amp;");
+                                       text = text.Replace ("<", "&lt;");
+                                       text = text.Replace (">", "&gt;");
+                                       
+                                       if (openAttribute) 
+                                       {
+                                               if (quoteChar == '"')
+                                                       text = text.Replace ("\"", "&quot;");
+                                               else
+                                                       text = text.Replace ("'", "&apos;");
+                                       }
                                }
 
                                if (!openAttribute)
+                               {
+                                       IndentingOverriden = true;
                                        CloseStartElement ();
-
+                               }
                                if (!openXmlLang && !openXmlSpace)
                                        w.Write (text);
-                               else {
+                               else 
+                               {
                                        if (openXmlLang)
                                                xmlLang = text;
-                                       else {
-                                               switch (text) {
+                                       else 
+                                       {
+                                               switch (text) 
+                                               {
                                                        case "default":
                                                                xmlSpace = XmlSpace.Default;
                                                                break;
@@ -586,8 +708,6 @@ namespace System.Xml
                                        }
                                }
                        }
-
-                       IndentingOverriden = true;
                }
 
                [MonoTODO]