XmlDocument.cs 26 KB

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