2 // System.Xml.XmlDeclaration
5 // Duncan Mak (duncan@ximian.com)
11 using System.Text.RegularExpressions;
15 public class XmlDeclaration : XmlLinkedNode
17 string encoding = "UTF-8"; // defaults to UTF-8
21 protected internal XmlDeclaration (string version, string encoding,
22 string standalone, XmlDocument doc)
28 if (standalone == null)
31 this.version = version;
32 this.encoding = encoding;
33 this.standalone = standalone;
36 public string Encoding {
37 get { return encoding; }
38 set { encoding = (value == null) ? String.Empty : value; }
41 public override string InnerText {
43 set { ParseInput (value); }
46 public override string LocalName {
50 public override string Name {
54 public override XmlNodeType NodeType {
55 get { return XmlNodeType.XmlDeclaration; }
58 public string Standalone {
59 get { return standalone; }
63 if (value.ToUpper() == "YES")
65 if (value.ToUpper() == "NO")
69 standalone = String.Empty;
73 public override string Value {
75 string formatEncoding = "";
76 string formatStandalone = "";
78 if (encoding != String.Empty)
79 formatEncoding = String.Format (" encoding=\"{0}\"", encoding);
81 if (standalone != String.Empty)
82 formatStandalone = String.Format (" standalone=\"{0}\"", standalone);
84 return String.Format ("version=\"{0}\"{1}{2}", Version, formatEncoding, formatStandalone);
86 set { ParseInput (value); }
89 public string Version {
90 get { return version; }
93 public override XmlNode CloneNode (bool deep)
95 return new XmlDeclaration (Version, Encoding, standalone, OwnerDocument);
98 public override void WriteContentTo (XmlWriter w) {}
100 public override void WriteTo (XmlWriter w)
102 // This doesn't seem to match up very well with w.WriteStartDocument()
103 // so writing out custom here.
104 w.WriteRaw (String.Format ("<?xml {0}?>", Value));
107 void ParseInput (string input)
109 // Encoding = input.Split (new char [] { ' ' }) [1].Split (new char [] { '=' }) [1];
110 // Standalone = input.Split (new char [] { ' ' }) [2].Split (new char [] { '=' }) [1];
111 Match m = XmlDeclRegex.Match(input);
113 throw new XmlException("illegal XML declaration format.");
114 // Version = m.Result("${ver}");
115 Encoding = m.Result("${enc}");
116 Standalone = m.Result("${sta}");
119 // This regular expression matches XMLDecl of XML specification BNF[23]
120 static Regex xmlDeclRegex;
121 Regex XmlDeclRegex
\r
125 if(xmlDeclRegex == null) xmlDeclRegex = new Regex(allMatch, RegexOptions.Compiled);
130 // This code makes some loss, but you may understand a bit easily.
131 const string verMatch = "\\s*version\\s*=\\s*(\\'(?<ver>.*?)\\'|\\\"(?<ver>.*?)\")";
132 const string encMatch = "\\s*encoding\\s*=\\s*(\\'(?<enc>.*?)\\'|\\\"(?<enc>.*?)\")";
133 const string staMatch = "\\s*standalone\\s*=\\s*(\\'(?<sta>.*?)\\'|\\\"(?<sta>.*?)\")";
134 const string allMatch = verMatch + "(" + encMatch + ")?(" + staMatch + ")?";