XmlDocument.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928
  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. protected 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. XmlReader xr = new XmlTextReader (filename);
  451. Load (xr);
  452. xr.Close ();
  453. }
  454. public virtual void Load (TextReader txtReader)
  455. {
  456. Load (new XmlTextReader (txtReader));
  457. }
  458. public virtual void Load (XmlReader xmlReader)
  459. {
  460. // Reset our document
  461. // For now this just means removing all our children but later this
  462. // may turn out o need to call a private method that resets other things
  463. // like properties we have, etc.
  464. RemoveAll ();
  465. this.baseURI = xmlReader.BaseURI;
  466. // create all contents with use of ReadNode()
  467. do {
  468. XmlNode n = ReadNode (xmlReader);
  469. if(n == null) break;
  470. AppendChild (n);
  471. } while (true);
  472. }
  473. public virtual void LoadXml (string xml)
  474. {
  475. XmlReader xmlReader = new XmlTextReader (new StringReader (xml));
  476. Load (xmlReader);
  477. }
  478. internal void onNodeChanged (XmlNode node, XmlNode Parent)
  479. {
  480. if (NodeChanged != null)
  481. NodeChanged (node, new XmlNodeChangedEventArgs
  482. (XmlNodeChangedAction.Change,
  483. node, Parent, Parent));
  484. }
  485. internal void onNodeChanging(XmlNode node, XmlNode Parent)
  486. {
  487. if (NodeChanging != null)
  488. NodeChanging (node, new XmlNodeChangedEventArgs
  489. (XmlNodeChangedAction.Change,
  490. node, Parent, Parent));
  491. }
  492. internal void onNodeInserted (XmlNode node, XmlNode newParent)
  493. {
  494. if (NodeInserted != null)
  495. NodeInserted (node, new XmlNodeChangedEventArgs
  496. (XmlNodeChangedAction.Insert,
  497. node, null, newParent));
  498. }
  499. internal void onNodeInserting (XmlNode node, XmlNode newParent)
  500. {
  501. if (NodeInserting != null)
  502. NodeInserting (node, new XmlNodeChangedEventArgs
  503. (XmlNodeChangedAction.Insert,
  504. node, null, newParent));
  505. }
  506. internal void onNodeRemoved (XmlNode node, XmlNode oldParent)
  507. {
  508. if (NodeRemoved != null)
  509. NodeRemoved (node, new XmlNodeChangedEventArgs
  510. (XmlNodeChangedAction.Remove,
  511. node, oldParent, null));
  512. }
  513. internal void onNodeRemoving (XmlNode node, XmlNode oldParent)
  514. {
  515. if (NodeRemoving != null)
  516. NodeRemoving (node, new XmlNodeChangedEventArgs
  517. (XmlNodeChangedAction.Remove,
  518. node, oldParent, null));
  519. }
  520. private void ParseName (string name, out string prefix, out string localName)
  521. {
  522. int indexOfColon = name.IndexOf (':');
  523. if (indexOfColon != -1) {
  524. prefix = name.Substring (0, indexOfColon);
  525. localName = name.Substring (indexOfColon + 1);
  526. } else {
  527. prefix = "";
  528. localName = name;
  529. }
  530. }
  531. // Checks that Element's name is valid
  532. private void CheckName (String name)
  533. {
  534. // TODO: others validations?
  535. if (name.IndexOf (" ") >= 0)
  536. throw new XmlException ("The ' ' characted cannot be included in a name");
  537. }
  538. // Reads XmlReader and creates Attribute Node.
  539. private XmlAttribute ReadAttributeNode(XmlReader reader)
  540. {
  541. if(reader.NodeType == XmlNodeType.Element)
  542. reader.MoveToFirstAttribute ();
  543. else if(reader.NodeType != XmlNodeType.Attribute)
  544. throw new InvalidOperationException (MakeReaderErrorMessage ("bad position to read attribute.", reader));
  545. XmlAttribute attribute = CreateAttribute (reader.Prefix, reader.LocalName, reader.NamespaceURI);
  546. ReadAttributeNodeValue (reader, attribute);
  547. // Keep the current reader position
  548. bool res;
  549. if (attribute.NamespaceURI == string.Empty || attribute.NamespaceURI == null)
  550. res = reader.MoveToAttribute (attribute.Name);
  551. else
  552. res = reader.MoveToAttribute (attribute.LocalName, attribute.NamespaceURI);
  553. return attribute;
  554. }
  555. // Reads attribute from XmlReader and then creates attribute value children. XmlAttribute also uses this.
  556. internal void ReadAttributeNodeValue(XmlReader reader, XmlAttribute attribute)
  557. {
  558. while(reader.ReadAttributeValue ()) {
  559. if(reader.NodeType == XmlNodeType.EntityReference)
  560. // FIXME: if DocumentType is available, then try to resolve it.
  561. attribute.AppendChild (CreateEntityReference (reader.Name));
  562. // FIXME: else if(NodeType == EndEntity) -- reset BaseURI and so on -- ;
  563. else
  564. // Children of Attribute is restricted to CharacterData and EntityReference (Comment is not allowed).
  565. attribute.AppendChild (CreateTextNode (reader.Value));
  566. }
  567. }
  568. [MonoTODO ("Child of entity is not simple Value string;Get prefix of NotationDecl")]
  569. public virtual XmlNode ReadNode(XmlReader reader)
  570. {
  571. XmlNode resultNode = null;
  572. XmlNode newNode = null;
  573. XmlNode currentNode = null;
  574. if (reader.ReadState == ReadState.Initial)
  575. reader.Read ();
  576. int startDepth = reader.Depth;
  577. bool ignoredWhitespace;
  578. bool reachedEOF = false;
  579. do {
  580. ignoredWhitespace = false;
  581. if (reader.NodeType == XmlNodeType.None)
  582. if (reachedEOF)
  583. throw new Exception ("XML Reader reached to end while reading node.");
  584. else
  585. reachedEOF = true;
  586. switch (reader.NodeType) {
  587. case XmlNodeType.Attribute:
  588. newNode = ReadAttributeNode (reader);
  589. break;
  590. case XmlNodeType.CDATA:
  591. newNode = CreateCDataSection (reader.Value);
  592. if(currentNode != null)
  593. currentNode.AppendChild (newNode);
  594. break;
  595. case XmlNodeType.Comment:
  596. newNode = CreateComment (reader.Value);
  597. if(currentNode != null)
  598. currentNode.AppendChild (newNode);
  599. break;
  600. case XmlNodeType.Element:
  601. XmlElement element = CreateElement (reader.Prefix, reader.LocalName, reader.NamespaceURI);
  602. element.IsEmpty = reader.IsEmptyElement;
  603. if(currentNode != null)
  604. currentNode.AppendChild (element);
  605. else
  606. resultNode = element;
  607. // set the element's attributes.
  608. while (reader.MoveToNextAttribute ()) {
  609. element.SetAttributeNode (ReadAttributeNode (reader));
  610. }
  611. reader.MoveToElement ();
  612. if (!reader.IsEmptyElement)
  613. currentNode = element;
  614. break;
  615. case XmlNodeType.EndElement:
  616. if (currentNode == null)
  617. throw new XmlException ("Unexpected end element.");
  618. else if (currentNode.Name != reader.Name)
  619. throw new XmlException (MakeReaderErrorMessage (String.Format ("mismatch end tag. Expected {0} but found {1}", currentNode.Name, reader.Name), reader));
  620. currentNode = currentNode.ParentNode;
  621. break;
  622. case XmlNodeType.EndEntity:
  623. break; // no operation
  624. case XmlNodeType.ProcessingInstruction:
  625. newNode = CreateProcessingInstruction (reader.Name, reader.Value);
  626. if(currentNode != null)
  627. currentNode.AppendChild (newNode);
  628. break;
  629. case XmlNodeType.Text:
  630. newNode = CreateTextNode (reader.Value);
  631. if(currentNode != null)
  632. currentNode.AppendChild (newNode);
  633. break;
  634. case XmlNodeType.XmlDeclaration:
  635. // empty strings are dummy, then gives over setting value contents to setter.
  636. newNode = CreateXmlDeclaration ("1.0" , String.Empty, String.Empty);
  637. ((XmlDeclaration)newNode).Value = reader.Value;
  638. if(currentNode != null)
  639. throw new XmlException (MakeReaderErrorMessage ("XmlDeclaration at invalid position.", reader));
  640. break;
  641. case XmlNodeType.DocumentType:
  642. // hack ;-)
  643. XmlTextReader xtReader = reader as XmlTextReader;
  644. if(xtReader == null) {
  645. // XmlTextReader doesn't allow such creation that starts reading from Doctype.
  646. /*
  647. xtReader = new XmlTextReader (reader.ReadOuterXml (),
  648. XmlNodeType.DocumentType,
  649. new XmlParserContext (NameTable, ConstructNamespaceManager(), XmlLang, XmlSpace));
  650. xtReader.Read ();
  651. */
  652. newNode = CreateDocumentType (reader.Name, reader ["PUBLIC"], reader ["SYSTEM"], reader.Value);
  653. } else {
  654. newNode = ReadDoctypeNode (xtReader);
  655. }
  656. if(currentNode != null)
  657. throw new XmlException (this.MakeReaderErrorMessage ("XmlDocumentType at invalid position.", reader));
  658. break;
  659. case XmlNodeType.EntityReference:
  660. newNode = CreateEntityReference (reader.Name);
  661. if(currentNode != null)
  662. currentNode.AppendChild (newNode);
  663. break;
  664. case XmlNodeType.SignificantWhitespace:
  665. newNode = CreateSignificantWhitespace (reader.Value);
  666. if(currentNode != null)
  667. currentNode.AppendChild (newNode);
  668. break;
  669. case XmlNodeType.Whitespace:
  670. if(PreserveWhitespace) {
  671. newNode = CreateWhitespace (reader.Value);
  672. if(currentNode != null)
  673. currentNode.AppendChild (newNode);
  674. }
  675. else
  676. ignoredWhitespace = true;
  677. break;
  678. }
  679. if (!(newNode is XmlAttribute) && !reader.Read ())
  680. break;
  681. } while (ignoredWhitespace || reader.Depth > startDepth ||
  682. (reader.Depth == startDepth && reader.NodeType == XmlNodeType.EndElement));
  683. if (startDepth != reader.Depth && reader.EOF)
  684. throw new XmlException ("Unexpected end of xml reader.");
  685. return resultNode != null ? resultNode : newNode;
  686. }
  687. private string MakeReaderErrorMessage (string message, XmlReader reader)
  688. {
  689. IXmlLineInfo li = reader as IXmlLineInfo;
  690. if (li != null)
  691. return String.Format ("{0} Line number = {1}, Inline position = {2}.", li.LineNumber, li.LinePosition);
  692. else
  693. return message;
  694. }
  695. private XmlDocumentType ReadDoctypeNode (XmlTextReader xtReader)
  696. {
  697. XmlDocumentType doctype = CreateDocumentType (xtReader.Name,
  698. xtReader.GetAttribute ("PUBLIC"),
  699. xtReader.GetAttribute ("SYSTEM"),
  700. xtReader.Value);
  701. DTDObjectModel subset = xtReader.currentSubset;
  702. foreach (DTDEntityDeclaration decl in subset.EntityDecls.Values) {
  703. XmlNode n = new XmlEntity (decl.Name, decl.NotationName,
  704. decl.PublicId, decl.SystemId, this);
  705. // FIXME: Value is more complex, similar to Attribute.
  706. n.insertBeforeIntern (this.CreateTextNode (decl.EntityValue), null);
  707. doctype.entities.Nodes.Add (n);
  708. }
  709. foreach (DTDNotationDeclaration decl in subset.NotationDecls.Values) {
  710. XmlNode n = new XmlNotation (decl.LocalName, decl.Prefix,
  711. decl.PublicId, decl.SystemId, this);
  712. doctype.notations.Nodes.Add (n);
  713. }
  714. foreach (DTDElementDeclaration decl in subset.ElementDecls.Values) {
  715. doctype.elementDecls.Add (decl.Name, decl);
  716. }
  717. foreach (DTDAttListDeclaration decl in subset.AttListDecls.Values) {
  718. doctype.attListDecls.Add (decl.Name, decl);
  719. }
  720. return doctype;
  721. }
  722. public virtual void Save(Stream outStream)
  723. {
  724. XmlTextWriter xmlWriter = new XmlTextWriter (outStream, Encoding.UTF8);
  725. xmlWriter.Formatting = Formatting.Indented;
  726. WriteContentTo (xmlWriter);
  727. xmlWriter.Close ();
  728. }
  729. public virtual void Save (string filename)
  730. {
  731. XmlTextWriter xmlWriter = new XmlTextWriter (filename, Encoding.UTF8);
  732. xmlWriter.Formatting = Formatting.Indented;
  733. WriteContentTo (xmlWriter);
  734. xmlWriter.Close ();
  735. }
  736. [MonoTODO]
  737. public virtual void Save (TextWriter writer)
  738. {
  739. XmlTextWriter xmlWriter = new XmlTextWriter (writer);
  740. xmlWriter.Formatting = Formatting.Indented;
  741. WriteContentTo (xmlWriter);
  742. xmlWriter.Flush ();
  743. }
  744. public virtual void Save (XmlWriter xmlWriter)
  745. {
  746. //
  747. // This should preserve white space if PreserveWhiteSpace is true
  748. //
  749. WriteContentTo (xmlWriter);
  750. xmlWriter.Flush ();
  751. }
  752. public override void WriteContentTo (XmlWriter w)
  753. {
  754. foreach(XmlNode childNode in ChildNodes) {
  755. childNode.WriteTo (w);
  756. }
  757. }
  758. public override void WriteTo (XmlWriter w)
  759. {
  760. WriteContentTo (w);
  761. }
  762. private void AddDefaultNameTableKeys ()
  763. {
  764. // The following keys are default of MS .NET Framework
  765. nameTable.Add ("#text");
  766. nameTable.Add ("xml");
  767. nameTable.Add ("xmlns");
  768. nameTable.Add ("#entity");
  769. nameTable.Add ("#document-fragment");
  770. nameTable.Add ("#comment");
  771. nameTable.Add ("space");
  772. nameTable.Add ("id");
  773. nameTable.Add ("#whitespace");
  774. nameTable.Add ("http://www.w3.org/2000/xmlns/");
  775. nameTable.Add ("#cdata-section");
  776. nameTable.Add ("lang");
  777. nameTable.Add ("#document");
  778. nameTable.Add ("#significant-whitespace");
  779. }
  780. #endregion
  781. }
  782. }