XmlDocument.cs 27 KB

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