XmlDocument.cs 27 KB

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