XmlDocument.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927
  1. //
  2. // System.Xml.XmlDocument
  3. //
  4. // Authors:
  5. // Daniel Weber ([email protected])
  6. // Kral Ferch <[email protected]>
  7. // Jason Diamond <[email protected]>
  8. // Miguel de Icaza ([email protected])
  9. // Duncan Mak ([email protected])
  10. // Atsushi Enomoto ([email protected])
  11. //
  12. // (C) 2001 Daniel Weber
  13. // (C) 2002 Kral Ferch, Jason Diamond, Miguel de Icaza, Duncan Mak,
  14. // Atsushi Enomoto
  15. //
  16. using System;
  17. using System.IO;
  18. using System.Text;
  19. using System.Xml.XPath;
  20. using System.Diagnostics;
  21. using System.Collections;
  22. using Mono.Xml;
  23. using Mono.Xml.Native;
  24. namespace System.Xml
  25. {
  26. public class XmlDocument : XmlNode
  27. {
  28. #region Fields
  29. XmlLinkedNode lastLinkedChild;
  30. XmlNameTable nameTable;
  31. string baseURI = String.Empty;
  32. XmlImplementation implementation;
  33. bool preserveWhitespace = false;
  34. XmlResolver resolver;
  35. #endregion
  36. #region Constructors
  37. public XmlDocument () : this (null, null)
  38. {
  39. }
  40. protected internal XmlDocument (XmlImplementation imp) : this (imp, null)
  41. {
  42. }
  43. public XmlDocument (XmlNameTable nt) : this (null, nt)
  44. {
  45. }
  46. XmlDocument (XmlImplementation impl, XmlNameTable nt) : base (null)
  47. {
  48. implementation = (impl != null) ? impl : new XmlImplementation ();
  49. nameTable = (nt != null) ? nt : implementation.internalNameTable;
  50. AddDefaultNameTableKeys ();
  51. }
  52. #endregion
  53. #region Events
  54. public event XmlNodeChangedEventHandler NodeChanged;
  55. public event XmlNodeChangedEventHandler NodeChanging;
  56. public event XmlNodeChangedEventHandler NodeInserted;
  57. public event XmlNodeChangedEventHandler NodeInserting;
  58. public event XmlNodeChangedEventHandler NodeRemoved;
  59. public event XmlNodeChangedEventHandler NodeRemoving;
  60. #endregion
  61. #region Properties
  62. public override string BaseURI {
  63. get {
  64. return baseURI;
  65. }
  66. }
  67. public XmlElement DocumentElement {
  68. get {
  69. XmlNode node = FirstChild;
  70. while (node != null) {
  71. if (node is XmlElement)
  72. break;
  73. node = node.NextSibling;
  74. }
  75. return node != null ? node as XmlElement : null;
  76. }
  77. }
  78. [MonoTODO("It doesn't have internal subset object model.")]
  79. public virtual XmlDocumentType DocumentType {
  80. get {
  81. foreach(XmlNode n in this.ChildNodes) {
  82. if(n.NodeType == XmlNodeType.DocumentType)
  83. return (XmlDocumentType)n;
  84. }
  85. return null;
  86. }
  87. }
  88. public XmlImplementation Implementation {
  89. get { return implementation; }
  90. }
  91. public override string InnerXml {
  92. get {
  93. return base.InnerXml;
  94. }
  95. set { // reason for overriding
  96. this.LoadXml (value);
  97. }
  98. }
  99. public override bool IsReadOnly {
  100. get { return false; }
  101. }
  102. internal override XmlLinkedNode LastLinkedChild {
  103. get {
  104. return lastLinkedChild;
  105. }
  106. set {
  107. lastLinkedChild = value;
  108. }
  109. }
  110. public override string LocalName {
  111. get { return "#document"; }
  112. }
  113. public override string Name {
  114. get { return "#document"; }
  115. }
  116. public XmlNameTable NameTable {
  117. get { return nameTable; }
  118. }
  119. public override XmlNodeType NodeType {
  120. get { return XmlNodeType.Document; }
  121. }
  122. internal override XPathNodeType XPathNodeType {
  123. get {
  124. return XPathNodeType.Root;
  125. }
  126. }
  127. public override XmlDocument OwnerDocument {
  128. get { return null; }
  129. }
  130. public bool PreserveWhitespace {
  131. get { return preserveWhitespace; }
  132. set { preserveWhitespace = value; }
  133. }
  134. internal override string XmlLang {
  135. get { return String.Empty; }
  136. }
  137. public virtual XmlResolver XmlResolver {
  138. set { resolver = value; }
  139. }
  140. internal override XmlSpace XmlSpace {
  141. get {
  142. return XmlSpace.None;
  143. }
  144. }
  145. #endregion
  146. #region Methods
  147. public override XmlNode CloneNode (bool deep)
  148. {
  149. XmlDocument doc = implementation.CreateDocument ();
  150. doc.baseURI = baseURI;
  151. doc.PreserveWhitespace = PreserveWhitespace; // required?
  152. if(deep)
  153. {
  154. foreach(XmlNode n in ChildNodes)
  155. doc.AppendChild (doc.ImportNode (n, deep));
  156. }
  157. return doc;
  158. }
  159. public XmlAttribute CreateAttribute (string name)
  160. {
  161. return CreateAttribute (name,
  162. name == "xmlns" ? "http://www.w3.org/2000/xmlns/" : String.Empty);
  163. }
  164. public XmlAttribute CreateAttribute (string qualifiedName, string namespaceURI)
  165. {
  166. string prefix;
  167. string localName;
  168. ParseName (qualifiedName, out prefix, out localName);
  169. return CreateAttribute (prefix, localName, namespaceURI);
  170. }
  171. public virtual XmlAttribute CreateAttribute (string prefix, string localName, string namespaceURI)
  172. {
  173. if ((localName == null) || (localName == String.Empty))
  174. throw new ArgumentException ("The attribute local name cannot be empty.");
  175. return new XmlAttribute (prefix, localName, namespaceURI, this);
  176. }
  177. public virtual XmlCDataSection CreateCDataSection (string data)
  178. {
  179. return new XmlCDataSection (data, this);
  180. }
  181. public virtual XmlComment CreateComment (string data)
  182. {
  183. return new XmlComment (data, this);
  184. }
  185. protected internal virtual XmlAttribute CreateDefaultAttribute (string prefix, string localName, string namespaceURI)
  186. {
  187. XmlAttribute attr = CreateAttribute (prefix, localName, namespaceURI);
  188. attr.isDefault = true;
  189. return attr;
  190. }
  191. public virtual XmlDocumentFragment CreateDocumentFragment ()
  192. {
  193. return new XmlDocumentFragment (this);
  194. }
  195. public virtual XmlDocumentType CreateDocumentType (string name, string publicId,
  196. string systemId, string internalSubset)
  197. {
  198. return new XmlDocumentType (name, publicId, systemId, internalSubset, this);
  199. }
  200. public XmlElement CreateElement (string name)
  201. {
  202. return CreateElement (name, String.Empty);
  203. }
  204. public XmlElement CreateElement (
  205. string qualifiedName,
  206. string namespaceURI)
  207. {
  208. string prefix;
  209. string localName;
  210. ParseName (qualifiedName, out prefix, out localName);
  211. return CreateElement (prefix, localName, namespaceURI);
  212. }
  213. public virtual XmlElement CreateElement (
  214. string prefix,
  215. string localName,
  216. string namespaceURI)
  217. {
  218. if ((localName == null) || (localName == String.Empty))
  219. throw new ArgumentException ("The local name for elements or attributes cannot be null or an empty string.");
  220. CheckName (localName);
  221. return new XmlElement (prefix != null ? prefix : String.Empty, localName, namespaceURI != null ? namespaceURI : String.Empty, this);
  222. }
  223. public virtual XmlEntityReference CreateEntityReference (string name)
  224. {
  225. return new XmlEntityReference (name, this);
  226. }
  227. internal virtual XPathNavigator CreateNavigator (XmlNode node)
  228. {
  229. return new XmlDocumentNavigator (node);
  230. }
  231. public virtual XmlNode CreateNode (
  232. string nodeTypeString,
  233. string name,
  234. string namespaceURI)
  235. {
  236. return CreateNode (GetNodeTypeFromString (nodeTypeString), name, namespaceURI);
  237. }
  238. public virtual XmlNode CreateNode (
  239. XmlNodeType type,
  240. string name,
  241. string namespaceURI)
  242. {
  243. string prefix = null;
  244. string localName = name;
  245. if ((type == XmlNodeType.Attribute) || (type == XmlNodeType.Element) || (type == XmlNodeType.EntityReference))
  246. ParseName (name, out prefix, out localName);
  247. return CreateNode (type, prefix, localName, namespaceURI);
  248. }
  249. public virtual XmlNode CreateNode (
  250. XmlNodeType type,
  251. string prefix,
  252. string name,
  253. string namespaceURI)
  254. {
  255. switch (type) {
  256. case XmlNodeType.Attribute: return CreateAttribute (prefix, name, namespaceURI);
  257. case XmlNodeType.CDATA: return CreateCDataSection (null);
  258. case XmlNodeType.Comment: return CreateComment (null);
  259. case XmlNodeType.Document: return new XmlDocument (); // TODO - test to see which constructor to use, i.e. use existing NameTable or not.
  260. case XmlNodeType.DocumentFragment: return CreateDocumentFragment ();
  261. case XmlNodeType.DocumentType: return CreateDocumentType (null, null, null, null);
  262. case XmlNodeType.Element: return CreateElement (prefix, name, namespaceURI);
  263. case XmlNodeType.EntityReference: return CreateEntityReference (null);
  264. case XmlNodeType.ProcessingInstruction: return CreateProcessingInstruction (null, null);
  265. case XmlNodeType.SignificantWhitespace: return CreateSignificantWhitespace (String.Empty);
  266. case XmlNodeType.Text: return CreateTextNode (null);
  267. case XmlNodeType.Whitespace: return CreateWhitespace (String.Empty);
  268. case XmlNodeType.XmlDeclaration: return CreateXmlDeclaration ("1.0", null, null);
  269. default: throw new ArgumentOutOfRangeException(String.Format("{0}\nParameter name: {1}",
  270. "Specified argument was out of the range of valid values", type.ToString ()));
  271. }
  272. }
  273. public virtual XmlProcessingInstruction CreateProcessingInstruction (
  274. string target,
  275. string data)
  276. {
  277. return new XmlProcessingInstruction (target, data, this);
  278. }
  279. public virtual XmlSignificantWhitespace CreateSignificantWhitespace (string text)
  280. {
  281. foreach (char c in text)
  282. if ((c != ' ') && (c != '\r') && (c != '\n') && (c != '\t'))
  283. throw new ArgumentException ("Invalid whitespace characters.");
  284. return new XmlSignificantWhitespace (text, this);
  285. }
  286. public virtual XmlText CreateTextNode (string text)
  287. {
  288. return new XmlText (text, this);
  289. }
  290. public virtual XmlWhitespace CreateWhitespace (string text)
  291. {
  292. foreach (char c in text)
  293. if ((c != ' ') && (c != '\r') && (c != '\n') && (c != '\t'))
  294. throw new ArgumentException ("Invalid whitespace characters.");
  295. return new XmlWhitespace (text, this);
  296. }
  297. public virtual XmlDeclaration CreateXmlDeclaration (string version, string encoding,
  298. string standalone)
  299. {
  300. if (version != "1.0")
  301. throw new ArgumentException ("version string is not correct.");
  302. if ((standalone != null && standalone != String.Empty) && !((standalone == "yes") || (standalone == "no")))
  303. throw new ArgumentException ("standalone string is not correct.");
  304. return new XmlDeclaration (version, encoding, standalone, this);
  305. }
  306. [MonoTODO]
  307. public virtual XmlElement GetElementById (string elementId)
  308. {
  309. throw new NotImplementedException ();
  310. }
  311. public virtual XmlNodeList GetElementsByTagName (string name)
  312. {
  313. ArrayList nodeArrayList = new ArrayList ();
  314. this.searchNodesRecursively (this, name, nodeArrayList);
  315. return new XmlNodeArrayList (nodeArrayList);
  316. }
  317. private void searchNodesRecursively (XmlNode argNode, string argName,
  318. ArrayList argArrayList)
  319. {
  320. XmlNodeList xmlNodeList = argNode.ChildNodes;
  321. foreach (XmlNode node in xmlNodeList){
  322. if (node.Name.Equals (argName))
  323. argArrayList.Add (node);
  324. else
  325. this.searchNodesRecursively (node, argName, argArrayList);
  326. }
  327. }
  328. private void searchNodesRecursively (XmlNode argNode, string argName, string argNamespaceURI,
  329. ArrayList argArrayList)
  330. {
  331. XmlNodeList xmlNodeList = argNode.ChildNodes;
  332. foreach (XmlNode node in xmlNodeList){
  333. if (node.LocalName.Equals (argName) && node.NamespaceURI.Equals (argNamespaceURI))
  334. argArrayList.Add (node);
  335. else
  336. this.searchNodesRecursively (node, argName, argNamespaceURI, argArrayList);
  337. }
  338. }
  339. public virtual XmlNodeList GetElementsByTagName (string localName, string namespaceURI)
  340. {
  341. ArrayList nodeArrayList = new ArrayList ();
  342. this.searchNodesRecursively (this, localName, namespaceURI, nodeArrayList);
  343. return new XmlNodeArrayList (nodeArrayList);
  344. }
  345. private XmlNodeType GetNodeTypeFromString (string nodeTypeString)
  346. {
  347. switch (nodeTypeString) {
  348. case "attribute": return XmlNodeType.Attribute;
  349. case "cdatasection": return XmlNodeType.CDATA;
  350. case "comment": return XmlNodeType.Comment;
  351. case "document": return XmlNodeType.Document;
  352. case "documentfragment": return XmlNodeType.DocumentFragment;
  353. case "documenttype": return XmlNodeType.DocumentType;
  354. case "element": return XmlNodeType.Element;
  355. case "entityreference": return XmlNodeType.EntityReference;
  356. case "processinginstruction": return XmlNodeType.ProcessingInstruction;
  357. case "significantwhitespace": return XmlNodeType.SignificantWhitespace;
  358. case "text": return XmlNodeType.Text;
  359. case "whitespace": return XmlNodeType.Whitespace;
  360. default:
  361. throw new ArgumentException(String.Format("The string doesn't represent any node type : {0}.", nodeTypeString));
  362. }
  363. }
  364. [MonoTODO("default attributes (of imported doc); Entity; Notation")]
  365. public virtual XmlNode ImportNode (XmlNode node, bool deep)
  366. {
  367. switch(node.NodeType)
  368. {
  369. case XmlNodeType.Attribute:
  370. {
  371. XmlAttribute src_att = node as XmlAttribute;
  372. XmlAttribute dst_att = this.CreateAttribute (src_att.Prefix, src_att.LocalName, src_att.NamespaceURI);
  373. dst_att.Value = src_att.Value; // always explicitly specified (whether source is specified or not)
  374. return dst_att;
  375. }
  376. case XmlNodeType.CDATA:
  377. return this.CreateCDataSection (node.Value);
  378. case XmlNodeType.Comment:
  379. return this.CreateComment (node.Value);
  380. case XmlNodeType.Document:
  381. throw new XmlException ("Document cannot be imported.");
  382. case XmlNodeType.DocumentFragment:
  383. {
  384. XmlDocumentFragment df = this.CreateDocumentFragment ();
  385. if(deep)
  386. {
  387. foreach(XmlNode n in node.ChildNodes)
  388. {
  389. df.AppendChild (this.ImportNode (n, deep));
  390. }
  391. }
  392. return df;
  393. }
  394. case XmlNodeType.DocumentType:
  395. throw new XmlException ("DocumentType cannot be imported.");
  396. case XmlNodeType.Element:
  397. {
  398. XmlElement src = (XmlElement)node;
  399. XmlElement dst = this.CreateElement (src.Prefix, src.LocalName, src.NamespaceURI);
  400. foreach(XmlAttribute attr in src.Attributes)
  401. {
  402. if(attr.Specified) // copies only specified attributes
  403. dst.SetAttributeNode ((XmlAttribute)this.ImportNode (attr, deep));
  404. if(DocumentType != null)
  405. {
  406. // TODO: create default attribute values
  407. }
  408. }
  409. if(deep)
  410. {
  411. foreach(XmlNode n in src.ChildNodes)
  412. dst.AppendChild (this.ImportNode (n, deep));
  413. }
  414. return dst;
  415. }
  416. case XmlNodeType.EndElement:
  417. throw new XmlException ("Illegal ImportNode call for NodeType.EndElement");
  418. case XmlNodeType.EndEntity:
  419. throw new XmlException ("Illegal ImportNode call for NodeType.EndEntity");
  420. case XmlNodeType.Entity:
  421. throw new NotImplementedException (); // TODO
  422. case XmlNodeType.EntityReference:
  423. return this.CreateEntityReference (node.Name);
  424. case XmlNodeType.None:
  425. throw new XmlException ("Illegal ImportNode call for NodeType.None");
  426. case XmlNodeType.Notation:
  427. throw new NotImplementedException (); // TODO
  428. case XmlNodeType.ProcessingInstruction:
  429. XmlProcessingInstruction pi = node as XmlProcessingInstruction;
  430. return this.CreateProcessingInstruction (pi.Target, pi.Data);
  431. case XmlNodeType.SignificantWhitespace:
  432. return this.CreateSignificantWhitespace (node.Value);
  433. case XmlNodeType.Text:
  434. return this.CreateTextNode (node.Value);
  435. case XmlNodeType.Whitespace:
  436. return this.CreateWhitespace (node.Value);
  437. case XmlNodeType.XmlDeclaration:
  438. XmlDeclaration srcDecl = node as XmlDeclaration;
  439. return this.CreateXmlDeclaration (srcDecl.Version, srcDecl.Encoding, srcDecl.Standalone);
  440. default:
  441. throw new NotImplementedException ();
  442. }
  443. }
  444. public virtual void Load (Stream inStream)
  445. {
  446. Load (new XmlTextReader (new XmlStreamReader (inStream)));
  447. }
  448. public virtual void Load (string filename)
  449. {
  450. Load (new XmlTextReader (filename));
  451. }
  452. public virtual void Load (TextReader txtReader)
  453. {
  454. Load (new XmlTextReader (txtReader));
  455. }
  456. public virtual void Load (XmlReader xmlReader)
  457. {
  458. // Reset our document
  459. // For now this just means removing all our children but later this
  460. // may turn out o need to call a private method that resets other things
  461. // like properties we have, etc.
  462. RemoveAll ();
  463. this.baseURI = xmlReader.BaseURI;
  464. // create all contents with use of ReadNode()
  465. do {
  466. XmlNode n = ReadNode (xmlReader);
  467. if(n == null) break;
  468. AppendChild (n);
  469. } while (true);
  470. xmlReader.Close ();
  471. }
  472. public virtual void LoadXml (string xml)
  473. {
  474. XmlReader xmlReader = new XmlTextReader (new StringReader (xml));
  475. Load (xmlReader);
  476. }
  477. internal void onNodeChanged (XmlNode node, XmlNode Parent)
  478. {
  479. if (NodeChanged != null)
  480. NodeChanged (node, new XmlNodeChangedEventArgs
  481. (XmlNodeChangedAction.Change,
  482. node, Parent, Parent));
  483. }
  484. internal void onNodeChanging(XmlNode node, XmlNode Parent)
  485. {
  486. if (NodeChanging != null)
  487. NodeChanging (node, new XmlNodeChangedEventArgs
  488. (XmlNodeChangedAction.Change,
  489. node, Parent, Parent));
  490. }
  491. internal void onNodeInserted (XmlNode node, XmlNode newParent)
  492. {
  493. if (NodeInserted != null)
  494. NodeInserted (node, new XmlNodeChangedEventArgs
  495. (XmlNodeChangedAction.Insert,
  496. node, null, newParent));
  497. }
  498. internal void onNodeInserting (XmlNode node, XmlNode newParent)
  499. {
  500. if (NodeInserting != null)
  501. NodeInserting (node, new XmlNodeChangedEventArgs
  502. (XmlNodeChangedAction.Insert,
  503. node, null, newParent));
  504. }
  505. internal void onNodeRemoved (XmlNode node, XmlNode oldParent)
  506. {
  507. if (NodeRemoved != null)
  508. NodeRemoved (node, new XmlNodeChangedEventArgs
  509. (XmlNodeChangedAction.Remove,
  510. node, oldParent, null));
  511. }
  512. internal void onNodeRemoving (XmlNode node, XmlNode oldParent)
  513. {
  514. if (NodeRemoving != null)
  515. NodeRemoving (node, new XmlNodeChangedEventArgs
  516. (XmlNodeChangedAction.Remove,
  517. node, oldParent, null));
  518. }
  519. private void ParseName (string name, out string prefix, out string localName)
  520. {
  521. int indexOfColon = name.IndexOf (':');
  522. if (indexOfColon != -1) {
  523. prefix = name.Substring (0, indexOfColon);
  524. localName = name.Substring (indexOfColon + 1);
  525. } else {
  526. prefix = "";
  527. localName = name;
  528. }
  529. }
  530. // Checks that Element's name is valid
  531. private void CheckName (String name)
  532. {
  533. // TODO: others validations?
  534. if (name.IndexOf (" ") >= 0)
  535. throw new XmlException ("The ' ' characted cannot be included in a name");
  536. }
  537. // Reads XmlReader and creates Attribute Node.
  538. private XmlAttribute ReadAttributeNode(XmlReader reader)
  539. {
  540. if(reader.NodeType == XmlNodeType.Element)
  541. reader.MoveToFirstAttribute ();
  542. else if(reader.NodeType != XmlNodeType.Attribute)
  543. throw new InvalidOperationException (MakeReaderErrorMessage ("bad position to read attribute.", reader));
  544. XmlAttribute attribute = CreateAttribute (reader.Prefix, reader.LocalName, reader.NamespaceURI);
  545. ReadAttributeNodeValue (reader, attribute);
  546. // Keep the current reader position
  547. bool res;
  548. if (attribute.NamespaceURI == string.Empty || attribute.NamespaceURI == null)
  549. res = reader.MoveToAttribute (attribute.Name);
  550. else
  551. res = reader.MoveToAttribute (attribute.LocalName, attribute.NamespaceURI);
  552. return attribute;
  553. }
  554. // Reads attribute from XmlReader and then creates attribute value children. XmlAttribute also uses this.
  555. internal void ReadAttributeNodeValue(XmlReader reader, XmlAttribute attribute)
  556. {
  557. while(reader.ReadAttributeValue ()) {
  558. if(reader.NodeType == XmlNodeType.EntityReference)
  559. // FIXME: if DocumentType is available, then try to resolve it.
  560. attribute.AppendChild (CreateEntityReference (reader.Name));
  561. // FIXME: else if(NodeType == EndEntity) -- reset BaseURI and so on -- ;
  562. else
  563. // Children of Attribute is restricted to CharacterData and EntityReference (Comment is not allowed).
  564. attribute.AppendChild (CreateTextNode (reader.Value));
  565. }
  566. }
  567. [MonoTODO ("Child of entity is not simple Value string;Get prefix of NotationDecl")]
  568. public virtual XmlNode ReadNode(XmlReader reader)
  569. {
  570. XmlNode resultNode = null;
  571. XmlNode newNode = null;
  572. XmlNode currentNode = null;
  573. if (reader.ReadState == ReadState.Initial)
  574. reader.Read ();
  575. int startDepth = reader.Depth;
  576. bool ignoredWhitespace;
  577. bool reachedEOF = false;
  578. do {
  579. ignoredWhitespace = false;
  580. if (reader.NodeType == XmlNodeType.None)
  581. if (reachedEOF)
  582. throw new Exception ("XML Reader reached to end while reading node.");
  583. else
  584. reachedEOF = true;
  585. switch (reader.NodeType) {
  586. case XmlNodeType.Attribute:
  587. newNode = ReadAttributeNode (reader);
  588. break;
  589. case XmlNodeType.CDATA:
  590. newNode = CreateCDataSection (reader.Value);
  591. if(currentNode != null)
  592. currentNode.AppendChild (newNode);
  593. break;
  594. case XmlNodeType.Comment:
  595. newNode = CreateComment (reader.Value);
  596. if(currentNode != null)
  597. currentNode.AppendChild (newNode);
  598. break;
  599. case XmlNodeType.Element:
  600. XmlElement element = CreateElement (reader.Prefix, reader.LocalName, reader.NamespaceURI);
  601. element.IsEmpty = reader.IsEmptyElement;
  602. if(currentNode != null)
  603. currentNode.AppendChild (element);
  604. else
  605. resultNode = element;
  606. // set the element's attributes.
  607. while (reader.MoveToNextAttribute ()) {
  608. element.SetAttributeNode (ReadAttributeNode (reader));
  609. }
  610. reader.MoveToElement ();
  611. if (!reader.IsEmptyElement)
  612. currentNode = element;
  613. break;
  614. case XmlNodeType.EndElement:
  615. if (currentNode == null)
  616. throw new XmlException ("Unexpected end element.");
  617. else if (currentNode.Name != reader.Name)
  618. throw new XmlException (MakeReaderErrorMessage (String.Format ("mismatch end tag. Expected {0} but found {1}", currentNode.Name, reader.Name), reader));
  619. currentNode = currentNode.ParentNode;
  620. break;
  621. case XmlNodeType.EndEntity:
  622. break; // no operation
  623. case XmlNodeType.ProcessingInstruction:
  624. newNode = CreateProcessingInstruction (reader.Name, reader.Value);
  625. if(currentNode != null)
  626. currentNode.AppendChild (newNode);
  627. break;
  628. case XmlNodeType.Text:
  629. newNode = CreateTextNode (reader.Value);
  630. if(currentNode != null)
  631. currentNode.AppendChild (newNode);
  632. break;
  633. case XmlNodeType.XmlDeclaration:
  634. // empty strings are dummy, then gives over setting value contents to setter.
  635. newNode = CreateXmlDeclaration ("1.0" , String.Empty, String.Empty);
  636. ((XmlDeclaration)newNode).Value = reader.Value;
  637. if(currentNode != null)
  638. throw new XmlException (MakeReaderErrorMessage ("XmlDeclaration at invalid position.", reader));
  639. break;
  640. case XmlNodeType.DocumentType:
  641. // hack ;-)
  642. XmlTextReader xtReader = reader as XmlTextReader;
  643. if(xtReader == null) {
  644. // XmlTextReader doesn't allow such creation that starts reading from Doctype.
  645. /*
  646. xtReader = new XmlTextReader (reader.ReadOuterXml (),
  647. XmlNodeType.DocumentType,
  648. new XmlParserContext (NameTable, ConstructNamespaceManager(), XmlLang, XmlSpace));
  649. xtReader.Read ();
  650. */
  651. newNode = CreateDocumentType (reader.Name, reader ["PUBLIC"], reader ["SYSTEM"], reader.Value);
  652. } else {
  653. newNode = ReadDoctypeNode (xtReader);
  654. }
  655. if(currentNode != null)
  656. throw new XmlException (this.MakeReaderErrorMessage ("XmlDocumentType at invalid position.", reader));
  657. break;
  658. case XmlNodeType.EntityReference:
  659. newNode = CreateEntityReference (reader.Name);
  660. if(currentNode != null)
  661. currentNode.AppendChild (newNode);
  662. break;
  663. case XmlNodeType.SignificantWhitespace:
  664. newNode = CreateSignificantWhitespace (reader.Value);
  665. if(currentNode != null)
  666. currentNode.AppendChild (newNode);
  667. break;
  668. case XmlNodeType.Whitespace:
  669. if(PreserveWhitespace) {
  670. newNode = CreateWhitespace (reader.Value);
  671. if(currentNode != null)
  672. currentNode.AppendChild (newNode);
  673. }
  674. else
  675. ignoredWhitespace = true;
  676. break;
  677. }
  678. if (!(newNode is XmlAttribute) && !reader.Read ())
  679. break;
  680. } while (ignoredWhitespace || reader.Depth > startDepth ||
  681. (reader.Depth == startDepth && reader.NodeType == XmlNodeType.EndElement));
  682. if (startDepth != reader.Depth && reader.EOF)
  683. throw new XmlException ("Unexpected end of xml reader.");
  684. return resultNode != null ? resultNode : newNode;
  685. }
  686. private string MakeReaderErrorMessage (string message, XmlReader reader)
  687. {
  688. IXmlLineInfo li = reader as IXmlLineInfo;
  689. if (li != null)
  690. return String.Format ("{0} Line number = {1}, Inline position = {2}.", li.LineNumber, li.LinePosition);
  691. else
  692. return message;
  693. }
  694. private XmlDocumentType ReadDoctypeNode (XmlTextReader xtReader)
  695. {
  696. XmlDocumentType doctype = CreateDocumentType (xtReader.Name,
  697. xtReader.GetAttribute ("PUBLIC"),
  698. xtReader.GetAttribute ("SYSTEM"),
  699. xtReader.Value);
  700. DTDObjectModel subset = xtReader.currentSubset;
  701. foreach (DTDEntityDeclaration decl in subset.EntityDecls.Values) {
  702. XmlNode n = new XmlEntity (decl.Name, decl.NotationName,
  703. decl.PublicId, decl.SystemId, this);
  704. // FIXME: Value is more complex, similar to Attribute.
  705. n.insertBeforeIntern (this.CreateTextNode (decl.EntityValue), null);
  706. doctype.entities.Nodes.Add (n);
  707. }
  708. foreach (DTDNotationDeclaration decl in subset.NotationDecls.Values) {
  709. XmlNode n = new XmlNotation (decl.LocalName, decl.Prefix,
  710. decl.PublicId, decl.SystemId, this);
  711. doctype.notations.Nodes.Add (n);
  712. }
  713. foreach (DTDElementDeclaration decl in subset.ElementDecls.Values) {
  714. doctype.elementDecls.Add (decl.Name, decl.Clone ());
  715. }
  716. foreach (DTDAttListDeclaration decl in subset.AttListDecls.Values) {
  717. doctype.attListDecls.Add (decl.Name, decl.Clone ());
  718. }
  719. return doctype;
  720. }
  721. public virtual void Save(Stream outStream)
  722. {
  723. XmlTextWriter xmlWriter = new XmlTextWriter (outStream, Encoding.UTF8);
  724. xmlWriter.Formatting = Formatting.Indented;
  725. WriteContentTo (xmlWriter);
  726. xmlWriter.Close ();
  727. }
  728. public virtual void Save (string filename)
  729. {
  730. XmlTextWriter xmlWriter = new XmlTextWriter (filename, Encoding.UTF8);
  731. xmlWriter.Formatting = Formatting.Indented;
  732. WriteContentTo (xmlWriter);
  733. xmlWriter.Close ();
  734. }
  735. [MonoTODO]
  736. public virtual void Save (TextWriter writer)
  737. {
  738. XmlTextWriter xmlWriter = new XmlTextWriter (writer);
  739. xmlWriter.Formatting = Formatting.Indented;
  740. WriteContentTo (xmlWriter);
  741. xmlWriter.Flush ();
  742. }
  743. public virtual void Save (XmlWriter xmlWriter)
  744. {
  745. //
  746. // This should preserve white space if PreserveWhiteSpace is true
  747. //
  748. WriteContentTo (xmlWriter);
  749. xmlWriter.Flush ();
  750. }
  751. public override void WriteContentTo (XmlWriter w)
  752. {
  753. foreach(XmlNode childNode in ChildNodes) {
  754. childNode.WriteTo (w);
  755. }
  756. }
  757. public override void WriteTo (XmlWriter w)
  758. {
  759. WriteContentTo (w);
  760. }
  761. private void AddDefaultNameTableKeys ()
  762. {
  763. // The following keys are default of MS .NET Framework
  764. nameTable.Add ("#text");
  765. nameTable.Add ("xml");
  766. nameTable.Add ("xmlns");
  767. nameTable.Add ("#entity");
  768. nameTable.Add ("#document-fragment");
  769. nameTable.Add ("#comment");
  770. nameTable.Add ("space");
  771. nameTable.Add ("id");
  772. nameTable.Add ("#whitespace");
  773. nameTable.Add ("http://www.w3.org/2000/xmlns/");
  774. nameTable.Add ("#cdata-section");
  775. nameTable.Add ("lang");
  776. nameTable.Add ("#document");
  777. nameTable.Add ("#significant-whitespace");
  778. }
  779. #endregion
  780. }
  781. }