2
0

XmlDocument.cs 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028
  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. // IF argument XmlReader can resolve entity,
  723. // ReadNode() also fills children _from it_.
  724. // In this case, it is not from doctype node.
  725. // (it is kind of sucky design, but it happens
  726. // anyways when we modify doctype node).
  727. //
  728. // It does not happen when !CanResolveEntity.
  729. // (In such case AppendChild() will resolve
  730. // entity content, as XmlEntityReference does.)
  731. if (reader.CanResolveEntity)
  732. {
  733. reader.ResolveEntity ();
  734. reader.Read ();
  735. for (XmlNode child; reader.NodeType != XmlNodeType.EndEntity && (child = ReadNode (reader)) != null;)
  736. n.InsertBefore (child, null, false, false);
  737. }
  738. break;
  739. case XmlNodeType.SignificantWhitespace:
  740. n = CreateSignificantWhitespace (reader.Value);
  741. break;
  742. case XmlNodeType.Whitespace:
  743. n = CreateWhitespace (reader.Value);
  744. break;
  745. case XmlNodeType.None:
  746. return null;
  747. default:
  748. // No idea why MS does throw NullReferenceException ;-P
  749. throw new NullReferenceException ("Unexpected node type " + reader.NodeType + ".");
  750. }
  751. reader.Read ();
  752. return n;
  753. }
  754. private string MakeReaderErrorMessage (string message, XmlReader reader)
  755. {
  756. IXmlLineInfo li = reader as IXmlLineInfo;
  757. if (li != null)
  758. return String.Format (CultureInfo.InvariantCulture, "{0} Line number = {1}, Inline position = {2}.", message, li.LineNumber, li.LinePosition);
  759. else
  760. return message;
  761. }
  762. internal void RemoveIdenticalAttribute (string id)
  763. {
  764. idTable.Remove (id);
  765. }
  766. public virtual void Save (Stream outStream)
  767. {
  768. XmlTextWriter xmlWriter = new XmlTextWriter (outStream, TextEncoding);
  769. if (!PreserveWhitespace)
  770. xmlWriter.Formatting = Formatting.Indented;
  771. WriteContentTo (xmlWriter);
  772. xmlWriter.Flush ();
  773. }
  774. public virtual void Save (string filename)
  775. {
  776. XmlTextWriter xmlWriter = new XmlTextWriter (filename, TextEncoding);
  777. try {
  778. if (!PreserveWhitespace)
  779. xmlWriter.Formatting = Formatting.Indented;
  780. WriteContentTo (xmlWriter);
  781. } finally {
  782. xmlWriter.Close ();
  783. }
  784. }
  785. public virtual void Save (TextWriter writer)
  786. {
  787. XmlTextWriter xmlWriter = new XmlTextWriter (writer);
  788. if (!PreserveWhitespace)
  789. xmlWriter.Formatting = Formatting.Indented;
  790. if (FirstChild != null && FirstChild.NodeType != XmlNodeType.XmlDeclaration)
  791. xmlWriter.WriteStartDocument ();
  792. WriteContentTo (xmlWriter);
  793. xmlWriter.WriteEndDocument ();
  794. xmlWriter.Flush ();
  795. }
  796. public virtual void Save (XmlWriter xmlWriter)
  797. {
  798. //
  799. // This should preserve white space if PreserveWhiteSpace is true
  800. //
  801. bool autoXmlDecl = FirstChild != null && FirstChild.NodeType != XmlNodeType.XmlDeclaration;
  802. if (autoXmlDecl)
  803. xmlWriter.WriteStartDocument ();
  804. WriteContentTo (xmlWriter);
  805. if (autoXmlDecl)
  806. xmlWriter.WriteEndDocument ();
  807. xmlWriter.Flush ();
  808. }
  809. public override void WriteContentTo (XmlWriter w)
  810. {
  811. for (int i = 0; i < ChildNodes.Count; i++)
  812. ChildNodes [i].WriteTo (w);
  813. }
  814. public override void WriteTo (XmlWriter w)
  815. {
  816. WriteContentTo (w);
  817. }
  818. private void AddDefaultNameTableKeys ()
  819. {
  820. // The following keys are default of MS .NET Framework
  821. nameTable.Add ("#text");
  822. nameTable.Add ("xml");
  823. nameTable.Add ("xmlns");
  824. nameTable.Add ("#entity");
  825. nameTable.Add ("#document-fragment");
  826. nameTable.Add ("#comment");
  827. nameTable.Add ("space");
  828. nameTable.Add ("id");
  829. nameTable.Add ("#whitespace");
  830. nameTable.Add ("http://www.w3.org/2000/xmlns/");
  831. nameTable.Add ("#cdata-section");
  832. nameTable.Add ("lang");
  833. nameTable.Add ("#document");
  834. nameTable.Add ("#significant-whitespace");
  835. }
  836. #if NET_2_0
  837. public void Validate (ValidationEventHandler handler)
  838. {
  839. Validate (handler, this,
  840. XmlSchemaValidationFlags.IgnoreValidationWarnings);
  841. }
  842. public void Validate (ValidationEventHandler handler,
  843. XmlNode node)
  844. {
  845. Validate (handler, node,
  846. XmlSchemaValidationFlags.IgnoreValidationWarnings |
  847. XmlSchemaValidationFlags.IgnoreIdentityConstraints);
  848. }
  849. private void Validate (ValidationEventHandler handler,
  850. XmlNode node, XmlSchemaValidationFlags flags)
  851. {
  852. XmlReaderSettings settings = new XmlReaderSettings ();
  853. settings.NameTable = NameTable;
  854. settings.Schemas = schemas;
  855. settings.Schemas.XmlResolver = resolver;
  856. settings.XmlResolver = resolver;
  857. settings.ValidationFlags = flags;
  858. settings.ValidationType = ValidationType.Schema;
  859. XmlReader r = XmlReader.Create (
  860. new XmlNodeReader (node), settings);
  861. while (!r.EOF)
  862. r.Read ();
  863. }
  864. #endif
  865. #endregion
  866. }
  867. }