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