XmlDocument.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952
  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. //
  17. // Permission is hereby granted, free of charge, to any person obtaining
  18. // a copy of this software and associated documentation files (the
  19. // "Software"), to deal in the Software without restriction, including
  20. // without limitation the rights to use, copy, modify, merge, publish,
  21. // distribute, sublicense, and/or sell copies of the Software, and to
  22. // permit persons to whom the Software is furnished to do so, subject to
  23. // the following conditions:
  24. //
  25. // The above copyright notice and this permission notice shall be
  26. // included in all copies or substantial portions of the Software.
  27. //
  28. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  29. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  30. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  31. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  32. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  33. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  34. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  35. //
  36. using System;
  37. using System.Globalization;
  38. using System.IO;
  39. using System.Text;
  40. using System.Xml.XPath;
  41. using System.Diagnostics;
  42. using System.Collections;
  43. using Mono.Xml;
  44. #if NET_2_0
  45. using Mono.Xml.XPath;
  46. #endif
  47. namespace System.Xml
  48. {
  49. public class XmlDocument : XmlNode
  50. {
  51. #region Fields
  52. XmlNameTable nameTable;
  53. string baseURI = String.Empty;
  54. XmlImplementation implementation;
  55. bool preserveWhitespace = false;
  56. XmlResolver resolver;
  57. Hashtable idTable = new Hashtable ();
  58. // MS.NET rejects undeclared entities _only_ during Load(),
  59. // while ReadNode() never rejects such node. So it signs
  60. // whether we are on Load() or not (MS.NET uses Loader class,
  61. // but we don't have to implement Load() as such)
  62. bool loadMode;
  63. #endregion
  64. #region Constructors
  65. public XmlDocument () : this (null, null)
  66. {
  67. }
  68. protected internal XmlDocument (XmlImplementation imp) : this (imp, null)
  69. {
  70. }
  71. public XmlDocument (XmlNameTable nt) : this (null, nt)
  72. {
  73. }
  74. XmlDocument (XmlImplementation impl, XmlNameTable nt) : base (null)
  75. {
  76. if (impl == null)
  77. implementation = new XmlImplementation ();
  78. else
  79. implementation = impl;
  80. nameTable = (nt != null) ? nt : implementation.InternalNameTable;
  81. AddDefaultNameTableKeys ();
  82. resolver = new XmlUrlResolver ();
  83. }
  84. #endregion
  85. #region Events
  86. public event XmlNodeChangedEventHandler NodeChanged;
  87. public event XmlNodeChangedEventHandler NodeChanging;
  88. public event XmlNodeChangedEventHandler NodeInserted;
  89. public event XmlNodeChangedEventHandler NodeInserting;
  90. public event XmlNodeChangedEventHandler NodeRemoved;
  91. public event XmlNodeChangedEventHandler NodeRemoving;
  92. #endregion
  93. #region Properties
  94. public override string BaseURI {
  95. get {
  96. return baseURI;
  97. }
  98. }
  99. public XmlElement DocumentElement {
  100. get {
  101. XmlNode node = FirstChild;
  102. while (node != null) {
  103. if (node is XmlElement)
  104. break;
  105. node = node.NextSibling;
  106. }
  107. return node != null ? node as XmlElement : null;
  108. }
  109. }
  110. public virtual XmlDocumentType DocumentType {
  111. get {
  112. for (int i = 0; i < ChildNodes.Count; i++) {
  113. XmlNode n = ChildNodes [i];
  114. if(n.NodeType == XmlNodeType.DocumentType)
  115. return (XmlDocumentType)n;
  116. }
  117. return null;
  118. }
  119. }
  120. public XmlImplementation Implementation {
  121. get { return implementation; }
  122. }
  123. public override string InnerXml {
  124. get {
  125. return base.InnerXml;
  126. }
  127. set { // reason for overriding
  128. this.LoadXml (value);
  129. }
  130. }
  131. public override bool IsReadOnly {
  132. get { return false; }
  133. }
  134. internal bool IsStandalone {
  135. get {
  136. return FirstChild != null &&
  137. FirstChild.NodeType == XmlNodeType.XmlDeclaration &&
  138. ((XmlDeclaration) this.FirstChild).Standalone == "yes";
  139. }
  140. }
  141. public override string LocalName {
  142. get { return "#document"; }
  143. }
  144. public override string Name {
  145. get { return "#document"; }
  146. }
  147. public XmlNameTable NameTable {
  148. get { return nameTable; }
  149. }
  150. public override XmlNodeType NodeType {
  151. get { return XmlNodeType.Document; }
  152. }
  153. internal override XPathNodeType XPathNodeType {
  154. get {
  155. return XPathNodeType.Root;
  156. }
  157. }
  158. public override XmlDocument OwnerDocument {
  159. get { return null; }
  160. }
  161. public bool PreserveWhitespace {
  162. get { return preserveWhitespace; }
  163. set { preserveWhitespace = value; }
  164. }
  165. internal XmlResolver Resolver {
  166. get { return resolver; }
  167. }
  168. internal override string XmlLang {
  169. get { return String.Empty; }
  170. }
  171. public virtual XmlResolver XmlResolver {
  172. set { resolver = value; }
  173. }
  174. internal override XmlSpace XmlSpace {
  175. get {
  176. return XmlSpace.None;
  177. }
  178. }
  179. internal Encoding TextEncoding {
  180. get {
  181. XmlDeclaration dec = FirstChild as XmlDeclaration;
  182. if (dec == null || dec.Encoding == "")
  183. return null;
  184. return Encoding.GetEncoding (dec.Encoding);
  185. }
  186. }
  187. #endregion
  188. #region Methods
  189. internal void AddIdenticalAttribute (XmlAttribute attr)
  190. {
  191. idTable [attr.Value] = attr;
  192. }
  193. public override XmlNode CloneNode (bool deep)
  194. {
  195. XmlDocument doc = implementation != null ? implementation.CreateDocument () : new XmlDocument ();
  196. doc.baseURI = baseURI;
  197. if(deep)
  198. {
  199. for (int i = 0; i < ChildNodes.Count; i++)
  200. doc.AppendChild (doc.ImportNode (ChildNodes [i], deep));
  201. }
  202. return doc;
  203. }
  204. public XmlAttribute CreateAttribute (string name)
  205. {
  206. string prefix;
  207. string localName;
  208. string namespaceURI = String.Empty;
  209. ParseName (name, out prefix, out localName);
  210. if (prefix == "xmlns" || (prefix == "" && localName == "xmlns"))
  211. namespaceURI = XmlNamespaceManager.XmlnsXmlns;
  212. else if (prefix == "xml")
  213. namespaceURI = XmlNamespaceManager.XmlnsXml;
  214. return CreateAttribute (prefix, localName, namespaceURI );
  215. }
  216. public XmlAttribute CreateAttribute (string qualifiedName, string namespaceURI)
  217. {
  218. string prefix;
  219. string localName;
  220. ParseName (qualifiedName, out prefix, out localName);
  221. return CreateAttribute (prefix, localName, namespaceURI);
  222. }
  223. public virtual XmlAttribute CreateAttribute (string prefix, string localName, string namespaceURI)
  224. {
  225. return CreateAttribute (prefix, localName, namespaceURI, false, true);
  226. }
  227. internal XmlAttribute CreateAttribute (string prefix, string localName, string namespaceURI, bool atomizedNames, bool checkNamespace)
  228. {
  229. if ((localName == null) || (localName == String.Empty))
  230. throw new ArgumentException ("The attribute local name cannot be empty.");
  231. return new XmlAttribute (prefix, localName, namespaceURI, this, atomizedNames, checkNamespace);
  232. }
  233. public virtual XmlCDataSection CreateCDataSection (string data)
  234. {
  235. return new XmlCDataSection (data, this);
  236. }
  237. public virtual XmlComment CreateComment (string data)
  238. {
  239. return new XmlComment (data, this);
  240. }
  241. protected internal virtual XmlAttribute CreateDefaultAttribute (string prefix, string localName, string namespaceURI)
  242. {
  243. XmlAttribute attr = CreateAttribute (prefix, localName, namespaceURI);
  244. attr.isDefault = true;
  245. return attr;
  246. }
  247. public virtual XmlDocumentFragment CreateDocumentFragment ()
  248. {
  249. return new XmlDocumentFragment (this);
  250. }
  251. public virtual XmlDocumentType CreateDocumentType (string name, string publicId,
  252. string systemId, string internalSubset)
  253. {
  254. return new XmlDocumentType (name, publicId, systemId, internalSubset, this);
  255. }
  256. private XmlDocumentType CreateDocumentType (DTDObjectModel dtd)
  257. {
  258. return new XmlDocumentType (dtd, this);
  259. }
  260. public XmlElement CreateElement (string name)
  261. {
  262. return CreateElement (name, String.Empty);
  263. }
  264. public XmlElement CreateElement (
  265. string qualifiedName,
  266. string namespaceURI)
  267. {
  268. string prefix;
  269. string localName;
  270. ParseName (qualifiedName, out prefix, out localName);
  271. return CreateElement (prefix, localName, namespaceURI);
  272. }
  273. public virtual XmlElement CreateElement (
  274. string prefix,
  275. string localName,
  276. string namespaceURI)
  277. {
  278. if ((localName == null) || (localName == String.Empty))
  279. throw new ArgumentException ("The local name for elements or attributes cannot be null or an empty string.");
  280. // LAMESPEC: MS.NET has a weird behavior that they can Load() from XmlTextReader
  281. // whose Namespaces = false, but their CreateElement() never allows qualified name.
  282. // I leave it as it is.
  283. return new XmlElement (prefix != null ? prefix : String.Empty, localName, namespaceURI != null ? namespaceURI : String.Empty, this, false);
  284. }
  285. public virtual XmlEntityReference CreateEntityReference (string name)
  286. {
  287. return new XmlEntityReference (name, this);
  288. }
  289. protected internal virtual XPathNavigator CreateNavigator (XmlNode node)
  290. {
  291. #if NET_2_0
  292. return new XPathEditableDocument (node).CreateNavigator ();
  293. #else
  294. return new XmlDocumentNavigator (node);
  295. #endif
  296. }
  297. public virtual XmlNode CreateNode (
  298. string nodeTypeString,
  299. string name,
  300. string namespaceURI)
  301. {
  302. return CreateNode (GetNodeTypeFromString (nodeTypeString), name, namespaceURI);
  303. }
  304. public virtual XmlNode CreateNode (
  305. XmlNodeType type,
  306. string name,
  307. string namespaceURI)
  308. {
  309. string prefix = null;
  310. string localName = name;
  311. if ((type == XmlNodeType.Attribute) || (type == XmlNodeType.Element) || (type == XmlNodeType.EntityReference))
  312. ParseName (name, out prefix, out localName);
  313. return CreateNode (type, prefix, localName, namespaceURI);
  314. }
  315. public virtual XmlNode CreateNode (
  316. XmlNodeType type,
  317. string prefix,
  318. string name,
  319. string namespaceURI)
  320. {
  321. switch (type) {
  322. case XmlNodeType.Attribute: return CreateAttribute (prefix, name, namespaceURI);
  323. case XmlNodeType.CDATA: return CreateCDataSection (null);
  324. case XmlNodeType.Comment: return CreateComment (null);
  325. case XmlNodeType.Document: return new XmlDocument ();
  326. case XmlNodeType.DocumentFragment: return CreateDocumentFragment ();
  327. case XmlNodeType.DocumentType: return CreateDocumentType (null, null, null, null);
  328. case XmlNodeType.Element: return CreateElement (prefix, name, namespaceURI);
  329. case XmlNodeType.EntityReference: return CreateEntityReference (null);
  330. case XmlNodeType.ProcessingInstruction: return CreateProcessingInstruction (null, null);
  331. case XmlNodeType.SignificantWhitespace: return CreateSignificantWhitespace (String.Empty);
  332. case XmlNodeType.Text: return CreateTextNode (null);
  333. case XmlNodeType.Whitespace: return CreateWhitespace (String.Empty);
  334. case XmlNodeType.XmlDeclaration: return CreateXmlDeclaration ("1.0", null, null);
  335. default: throw new ArgumentOutOfRangeException(String.Format("{0}\nParameter name: {1}",
  336. "Specified argument was out of the range of valid values", type.ToString ()));
  337. }
  338. }
  339. public virtual XmlProcessingInstruction CreateProcessingInstruction (
  340. string target,
  341. string data)
  342. {
  343. return new XmlProcessingInstruction (target, data, this);
  344. }
  345. public virtual XmlSignificantWhitespace CreateSignificantWhitespace (string text)
  346. {
  347. if (!XmlChar.IsWhitespace (text))
  348. throw new ArgumentException ("Invalid whitespace characters.");
  349. return new XmlSignificantWhitespace (text, this);
  350. }
  351. public virtual XmlText CreateTextNode (string text)
  352. {
  353. return new XmlText (text, this);
  354. }
  355. public virtual XmlWhitespace CreateWhitespace (string text)
  356. {
  357. if (!XmlChar.IsWhitespace (text))
  358. throw new ArgumentException ("Invalid whitespace characters.");
  359. return new XmlWhitespace (text, this);
  360. }
  361. public virtual XmlDeclaration CreateXmlDeclaration (string version, string encoding,
  362. string standalone)
  363. {
  364. if (version != "1.0")
  365. throw new ArgumentException ("version string is not correct.");
  366. if ((standalone != null && standalone != String.Empty) && !((standalone == "yes") || (standalone == "no")))
  367. throw new ArgumentException ("standalone string is not correct.");
  368. return new XmlDeclaration (version, encoding, standalone, this);
  369. }
  370. // FIXME: Currently XmlAttributeCollection.SetNamedItem() does
  371. // add to the identity table, but in fact I delayed identity
  372. // check on GetIdenticalAttribute. To make such way complete,
  373. // we have to use MultiMap, not Hashtable.
  374. //
  375. // Well, MS.NET is also fragile around here.
  376. public virtual XmlElement GetElementById (string elementId)
  377. {
  378. XmlAttribute attr = GetIdenticalAttribute (elementId);
  379. return attr != null ? attr.OwnerElement : null;
  380. }
  381. public virtual XmlNodeList GetElementsByTagName (string name)
  382. {
  383. ArrayList nodeArrayList = new ArrayList ();
  384. this.SearchDescendantElements (name, name == "*", nodeArrayList);
  385. return new XmlNodeArrayList (nodeArrayList);
  386. }
  387. public virtual XmlNodeList GetElementsByTagName (string localName, string namespaceURI)
  388. {
  389. ArrayList nodeArrayList = new ArrayList ();
  390. this.SearchDescendantElements (localName, localName == "*", namespaceURI, namespaceURI == "*", nodeArrayList);
  391. return new XmlNodeArrayList (nodeArrayList);
  392. }
  393. private XmlNodeType GetNodeTypeFromString (string nodeTypeString)
  394. {
  395. switch (nodeTypeString) {
  396. case "attribute": return XmlNodeType.Attribute;
  397. case "cdatasection": return XmlNodeType.CDATA;
  398. case "comment": return XmlNodeType.Comment;
  399. case "document": return XmlNodeType.Document;
  400. case "documentfragment": return XmlNodeType.DocumentFragment;
  401. case "documenttype": return XmlNodeType.DocumentType;
  402. case "element": return XmlNodeType.Element;
  403. case "entityreference": return XmlNodeType.EntityReference;
  404. case "processinginstruction": return XmlNodeType.ProcessingInstruction;
  405. case "significantwhitespace": return XmlNodeType.SignificantWhitespace;
  406. case "text": return XmlNodeType.Text;
  407. case "whitespace": return XmlNodeType.Whitespace;
  408. default:
  409. throw new ArgumentException(String.Format("The string doesn't represent any node type : {0}.", nodeTypeString));
  410. }
  411. }
  412. internal XmlAttribute GetIdenticalAttribute (string id)
  413. {
  414. XmlAttribute attr = this.idTable [id] as XmlAttribute;
  415. if (attr == null)
  416. return null;
  417. if (attr.OwnerElement == null || !attr.OwnerElement.IsRooted) {
  418. // idTable.Remove (id);
  419. return null;
  420. }
  421. return attr;
  422. }
  423. public virtual XmlNode ImportNode (XmlNode node, bool deep)
  424. {
  425. if (node == null)
  426. throw new NullReferenceException ("Null node cannot be imported.");
  427. switch (node.NodeType) {
  428. case XmlNodeType.Attribute:
  429. XmlAttribute srcAtt = node as XmlAttribute;
  430. XmlAttribute dstAtt = this.CreateAttribute (srcAtt.Prefix, srcAtt.LocalName, srcAtt.NamespaceURI);
  431. for (int i = 0; i < srcAtt.ChildNodes.Count; i++)
  432. dstAtt.AppendChild (this.ImportNode (srcAtt.ChildNodes [i], deep));
  433. return dstAtt;
  434. case XmlNodeType.CDATA:
  435. return this.CreateCDataSection (node.Value);
  436. case XmlNodeType.Comment:
  437. return this.CreateComment (node.Value);
  438. case XmlNodeType.Document:
  439. throw new XmlException ("Document cannot be imported.");
  440. case XmlNodeType.DocumentFragment:
  441. XmlDocumentFragment df = this.CreateDocumentFragment ();
  442. if(deep)
  443. for (int i = 0; i < node.ChildNodes.Count; i++)
  444. df.AppendChild (this.ImportNode (node.ChildNodes [i], deep));
  445. return df;
  446. case XmlNodeType.DocumentType:
  447. throw new XmlException ("DocumentType cannot be imported.");
  448. case XmlNodeType.Element:
  449. XmlElement src = (XmlElement)node;
  450. XmlElement dst = this.CreateElement (src.Prefix, src.LocalName, src.NamespaceURI);
  451. for (int i = 0; i < src.Attributes.Count; i++) {
  452. XmlAttribute attr = src.Attributes [i];
  453. if(attr.Specified) // copies only specified attributes
  454. dst.SetAttributeNode ((XmlAttribute) this.ImportNode (attr, deep));
  455. }
  456. if(deep)
  457. for (int i = 0; i < src.ChildNodes.Count; i++)
  458. dst.AppendChild (this.ImportNode (src.ChildNodes [i], deep));
  459. return dst;
  460. case XmlNodeType.EndElement:
  461. throw new XmlException ("Illegal ImportNode call for NodeType.EndElement");
  462. case XmlNodeType.EndEntity:
  463. throw new XmlException ("Illegal ImportNode call for NodeType.EndEntity");
  464. case XmlNodeType.EntityReference:
  465. return this.CreateEntityReference (node.Name);
  466. case XmlNodeType.None:
  467. throw new XmlException ("Illegal ImportNode call for NodeType.None");
  468. case XmlNodeType.ProcessingInstruction:
  469. XmlProcessingInstruction pi = node as XmlProcessingInstruction;
  470. return this.CreateProcessingInstruction (pi.Target, pi.Data);
  471. case XmlNodeType.SignificantWhitespace:
  472. return this.CreateSignificantWhitespace (node.Value);
  473. case XmlNodeType.Text:
  474. return this.CreateTextNode (node.Value);
  475. case XmlNodeType.Whitespace:
  476. return this.CreateWhitespace (node.Value);
  477. case XmlNodeType.XmlDeclaration:
  478. XmlDeclaration srcDecl = node as XmlDeclaration;
  479. return this.CreateXmlDeclaration (srcDecl.Version, srcDecl.Encoding, srcDecl.Standalone);
  480. default:
  481. throw new InvalidOperationException ("Cannot import specified node type: " + node.NodeType);
  482. }
  483. }
  484. public virtual void Load (Stream inStream)
  485. {
  486. XmlTextReader reader = new XmlTextReader (inStream, NameTable);
  487. reader.XmlResolver = resolver;
  488. Load (reader);
  489. }
  490. public virtual void Load (string filename)
  491. {
  492. XmlTextReader xr = null;
  493. try {
  494. xr = new XmlTextReader (filename, NameTable);
  495. xr.XmlResolver = resolver;
  496. Load (xr);
  497. } finally {
  498. if (xr != null)
  499. xr.Close ();
  500. }
  501. }
  502. public virtual void Load (TextReader txtReader)
  503. {
  504. XmlTextReader xr = new XmlTextReader (txtReader, NameTable);
  505. xr.XmlResolver = resolver;
  506. Load (xr);
  507. }
  508. public virtual void Load (XmlReader xmlReader)
  509. {
  510. // Reset our document
  511. // For now this just means removing all our children but later this
  512. // may turn out o need to call a private method that resets other things
  513. // like properties we have, etc.
  514. RemoveAll ();
  515. this.baseURI = xmlReader.BaseURI;
  516. // create all contents with use of ReadNode()
  517. try {
  518. loadMode = true;
  519. do {
  520. XmlNode n = ReadNode (xmlReader);
  521. if (n == null)
  522. break;
  523. if (preserveWhitespace || n.NodeType != XmlNodeType.Whitespace)
  524. AppendChild (n);
  525. } while (true);
  526. } finally {
  527. loadMode = false;
  528. }
  529. }
  530. public virtual void LoadXml (string xml)
  531. {
  532. XmlTextReader xmlReader = new XmlTextReader (
  533. xml,
  534. XmlNodeType.Document,
  535. new XmlParserContext (NameTable, null, null, XmlSpace.None));
  536. try {
  537. xmlReader.XmlResolver = resolver;
  538. Load (xmlReader);
  539. } finally {
  540. xmlReader.Close ();
  541. }
  542. }
  543. internal void onNodeChanged (XmlNode node, XmlNode parent, string oldValue, string newValue)
  544. {
  545. if (NodeChanged != null)
  546. NodeChanged (node, new XmlNodeChangedEventArgs
  547. (XmlNodeChangedAction.Change,
  548. node, parent, oldValue, newValue));
  549. }
  550. internal void onNodeChanging(XmlNode node, XmlNode parent, string oldValue, string newValue)
  551. {
  552. if (node.IsReadOnly)
  553. throw new ArgumentException ("Node is read-only.");
  554. if (NodeChanging != null)
  555. NodeChanging (node, new XmlNodeChangedEventArgs
  556. (XmlNodeChangedAction.Change,
  557. node, parent, oldValue, newValue));
  558. }
  559. internal void onNodeInserted (XmlNode node, XmlNode newParent)
  560. {
  561. if (NodeInserted != null)
  562. NodeInserted (node, new XmlNodeChangedEventArgs
  563. (XmlNodeChangedAction.Insert,
  564. node, null, newParent));
  565. }
  566. internal void onNodeInserting (XmlNode node, XmlNode newParent)
  567. {
  568. if (NodeInserting != null)
  569. NodeInserting (node, new XmlNodeChangedEventArgs
  570. (XmlNodeChangedAction.Insert,
  571. node, null, newParent));
  572. }
  573. internal void onNodeRemoved (XmlNode node, XmlNode oldParent)
  574. {
  575. if (NodeRemoved != null)
  576. NodeRemoved (node, new XmlNodeChangedEventArgs
  577. (XmlNodeChangedAction.Remove,
  578. node, oldParent, null));
  579. }
  580. internal void onNodeRemoving (XmlNode node, XmlNode oldParent)
  581. {
  582. if (NodeRemoving != null)
  583. NodeRemoving (node, new XmlNodeChangedEventArgs
  584. (XmlNodeChangedAction.Remove,
  585. node, oldParent, null));
  586. }
  587. private void ParseName (string name, out string prefix, out string localName)
  588. {
  589. int indexOfColon = name.IndexOf (':');
  590. if (indexOfColon != -1) {
  591. prefix = name.Substring (0, indexOfColon);
  592. localName = name.Substring (indexOfColon + 1);
  593. } else {
  594. prefix = "";
  595. localName = name;
  596. }
  597. }
  598. // Reads XmlReader and creates Attribute Node.
  599. private XmlAttribute ReadAttributeNode(XmlReader reader)
  600. {
  601. if(reader.NodeType == XmlNodeType.Element)
  602. reader.MoveToFirstAttribute ();
  603. else if(reader.NodeType != XmlNodeType.Attribute)
  604. throw new InvalidOperationException (MakeReaderErrorMessage ("bad position to read attribute.", reader));
  605. XmlAttribute attribute = CreateAttribute (reader.Prefix, reader.LocalName, reader.NamespaceURI, false, false); // different NameTable
  606. ReadAttributeNodeValue (reader, attribute);
  607. // Keep the current reader position
  608. bool res;
  609. if (attribute.NamespaceURI == string.Empty || attribute.NamespaceURI == null)
  610. res = reader.MoveToAttribute (attribute.Name);
  611. else
  612. res = reader.MoveToAttribute (attribute.LocalName, attribute.NamespaceURI);
  613. if (reader.IsDefault)
  614. attribute.SetDefault ();
  615. return attribute;
  616. }
  617. // Reads attribute from XmlReader and then creates attribute value children. XmlAttribute also uses this.
  618. internal void ReadAttributeNodeValue (XmlReader reader, XmlAttribute attribute)
  619. {
  620. while (reader.ReadAttributeValue ()) {
  621. if (reader.NodeType == XmlNodeType.EntityReference)
  622. attribute.AppendChild (CreateEntityReference (reader.Name));
  623. else
  624. // Children of Attribute is restricted to CharacterData and EntityReference (Comment is not allowed).
  625. attribute.AppendChild (CreateTextNode (reader.Value));
  626. }
  627. }
  628. public virtual XmlNode ReadNode (XmlReader reader)
  629. {
  630. switch (reader.ReadState) {
  631. case ReadState.Interactive:
  632. break;
  633. case ReadState.Initial:
  634. reader.Read ();
  635. break;
  636. default:
  637. return null;
  638. }
  639. XmlNode n;
  640. switch (reader.NodeType) {
  641. case XmlNodeType.Attribute:
  642. return ReadAttributeNode (reader);
  643. case XmlNodeType.CDATA:
  644. n = CreateCDataSection (reader.Value);
  645. break;
  646. case XmlNodeType.Comment:
  647. n = CreateComment (reader.Value);
  648. break;
  649. case XmlNodeType.Element:
  650. XmlElement element = CreateElement (reader.Prefix, reader.LocalName, reader.NamespaceURI);
  651. element.IsEmpty = reader.IsEmptyElement;
  652. // set the element's attributes.
  653. if (reader.MoveToFirstAttribute ()) {
  654. do {
  655. element.SetAttributeNode (ReadAttributeNode (reader));
  656. } while (reader.MoveToNextAttribute ());
  657. reader.MoveToElement ();
  658. }
  659. int depth = reader.Depth;
  660. if (element.IsEmpty) {
  661. n = element;
  662. break;
  663. }
  664. reader.Read ();
  665. while (reader.Depth > depth) {
  666. n = ReadNode (reader);
  667. if (preserveWhitespace || n.NodeType != XmlNodeType.Whitespace)
  668. element.AppendChild (n);
  669. }
  670. n = element;
  671. break;
  672. case XmlNodeType.ProcessingInstruction:
  673. n = CreateProcessingInstruction (reader.Name, reader.Value);
  674. break;
  675. case XmlNodeType.Text:
  676. n = CreateTextNode (reader.Value);
  677. break;
  678. case XmlNodeType.XmlDeclaration:
  679. n = CreateXmlDeclaration ("1.0" , String.Empty, String.Empty);
  680. n.Value = reader.Value;
  681. break;
  682. case XmlNodeType.DocumentType:
  683. DTDObjectModel dtd = null;
  684. IHasXmlParserContext ctxReader = reader as IHasXmlParserContext;
  685. if (ctxReader != null)
  686. dtd = ctxReader.ParserContext.Dtd;
  687. if (dtd != null)
  688. n = CreateDocumentType (dtd);
  689. else
  690. n = CreateDocumentType (reader.Name, reader ["PUBLIC"], reader ["SYSTEM"], reader.Value);
  691. break;
  692. case XmlNodeType.EntityReference:
  693. if (this.loadMode && this.DocumentType != null &&
  694. DocumentType.Entities.GetNamedItem (reader.Name) == null)
  695. throw new XmlException ("Reference to undeclared entity was found.");
  696. n = CreateEntityReference (reader.Name);
  697. break;
  698. case XmlNodeType.SignificantWhitespace:
  699. n = CreateSignificantWhitespace (reader.Value);
  700. break;
  701. case XmlNodeType.Whitespace:
  702. n = CreateWhitespace (reader.Value);
  703. break;
  704. case XmlNodeType.None:
  705. return null;
  706. default:
  707. // No idea why MS does throw NullReferenceException ;-P
  708. throw new NullReferenceException ("Unexpected node type " + reader.NodeType + ".");
  709. }
  710. reader.Read ();
  711. return n;
  712. }
  713. private string MakeReaderErrorMessage (string message, XmlReader reader)
  714. {
  715. IXmlLineInfo li = reader as IXmlLineInfo;
  716. if (li != null)
  717. return String.Format (CultureInfo.InvariantCulture, "{0} Line number = {1}, Inline position = {2}.", message, li.LineNumber, li.LinePosition);
  718. else
  719. return message;
  720. }
  721. internal void RemoveIdenticalAttribute (string id)
  722. {
  723. idTable.Remove (id);
  724. }
  725. public virtual void Save (Stream outStream)
  726. {
  727. XmlTextWriter xmlWriter = new XmlTextWriter (outStream, TextEncoding);
  728. if (!PreserveWhitespace)
  729. xmlWriter.Formatting = Formatting.Indented;
  730. WriteContentTo (xmlWriter);
  731. xmlWriter.Flush ();
  732. }
  733. public virtual void Save (string filename)
  734. {
  735. XmlTextWriter xmlWriter = new XmlTextWriter (filename, TextEncoding);
  736. try {
  737. if (!PreserveWhitespace)
  738. xmlWriter.Formatting = Formatting.Indented;
  739. WriteContentTo (xmlWriter);
  740. } finally {
  741. xmlWriter.Close ();
  742. }
  743. }
  744. public virtual void Save (TextWriter writer)
  745. {
  746. XmlTextWriter xmlWriter = new XmlTextWriter (writer);
  747. if (!PreserveWhitespace)
  748. xmlWriter.Formatting = Formatting.Indented;
  749. if (FirstChild != null && FirstChild.NodeType != XmlNodeType.XmlDeclaration)
  750. xmlWriter.WriteStartDocument ();
  751. WriteContentTo (xmlWriter);
  752. xmlWriter.WriteEndDocument ();
  753. xmlWriter.Flush ();
  754. }
  755. public virtual void Save (XmlWriter xmlWriter)
  756. {
  757. //
  758. // This should preserve white space if PreserveWhiteSpace is true
  759. //
  760. bool autoXmlDecl = FirstChild != null && FirstChild.NodeType != XmlNodeType.XmlDeclaration;
  761. if (autoXmlDecl)
  762. xmlWriter.WriteStartDocument ();
  763. WriteContentTo (xmlWriter);
  764. if (autoXmlDecl)
  765. xmlWriter.WriteEndDocument ();
  766. xmlWriter.Flush ();
  767. }
  768. public override void WriteContentTo (XmlWriter w)
  769. {
  770. for (int i = 0; i < ChildNodes.Count; i++)
  771. ChildNodes [i].WriteTo (w);
  772. }
  773. public override void WriteTo (XmlWriter w)
  774. {
  775. WriteContentTo (w);
  776. }
  777. private void AddDefaultNameTableKeys ()
  778. {
  779. // The following keys are default of MS .NET Framework
  780. nameTable.Add ("#text");
  781. nameTable.Add ("xml");
  782. nameTable.Add ("xmlns");
  783. nameTable.Add ("#entity");
  784. nameTable.Add ("#document-fragment");
  785. nameTable.Add ("#comment");
  786. nameTable.Add ("space");
  787. nameTable.Add ("id");
  788. nameTable.Add ("#whitespace");
  789. nameTable.Add ("http://www.w3.org/2000/xmlns/");
  790. nameTable.Add ("#cdata-section");
  791. nameTable.Add ("lang");
  792. nameTable.Add ("#document");
  793. nameTable.Add ("#significant-whitespace");
  794. }
  795. #endregion
  796. }
  797. }