XmlDocument.cs 28 KB

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