XmlDocument.cs 28 KB

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