XmlDocument.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029
  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. // Copyright (C) 2005 Novell, Inc (http://www.novell.com)
  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.Globalization;
  37. using System.IO;
  38. using System.Security.Permissions;
  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. [PermissionSet (SecurityAction.InheritanceDemand, Unrestricted = true)]
  266. public virtual XmlDocumentType CreateDocumentType (string name, string publicId,
  267. string systemId, string internalSubset)
  268. {
  269. return new XmlDocumentType (name, publicId, systemId, internalSubset, this);
  270. }
  271. private XmlDocumentType CreateDocumentType (DTDObjectModel dtd)
  272. {
  273. return new XmlDocumentType (dtd, this);
  274. }
  275. public XmlElement CreateElement (string name)
  276. {
  277. return CreateElement (name, String.Empty);
  278. }
  279. public XmlElement CreateElement (
  280. string qualifiedName,
  281. string namespaceURI)
  282. {
  283. string prefix;
  284. string localName;
  285. ParseName (qualifiedName, out prefix, out localName);
  286. return CreateElement (prefix, localName, namespaceURI);
  287. }
  288. public virtual XmlElement CreateElement (
  289. string prefix,
  290. string localName,
  291. string namespaceURI)
  292. {
  293. if ((localName == null) || (localName == String.Empty))
  294. throw new ArgumentException ("The local name for elements or attributes cannot be null or an empty string.");
  295. // LAMESPEC: MS.NET has a weird behavior that they can Load() from XmlTextReader
  296. // whose Namespaces = false, but their CreateElement() never allows qualified name.
  297. // I leave it as it is.
  298. return new XmlElement (prefix != null ? prefix : String.Empty, localName, namespaceURI != null ? namespaceURI : String.Empty, this, false);
  299. }
  300. public virtual XmlEntityReference CreateEntityReference (string name)
  301. {
  302. return new XmlEntityReference (name, this);
  303. }
  304. protected internal virtual XPathNavigator CreateNavigator (XmlNode node)
  305. {
  306. #if NET_2_0
  307. return new XPathEditableDocument (node).CreateNavigator ();
  308. #else
  309. return new XmlDocumentNavigator (node);
  310. #endif
  311. }
  312. public virtual XmlNode CreateNode (
  313. string nodeTypeString,
  314. string name,
  315. string namespaceURI)
  316. {
  317. return CreateNode (GetNodeTypeFromString (nodeTypeString), name, namespaceURI);
  318. }
  319. public virtual XmlNode CreateNode (
  320. XmlNodeType type,
  321. string name,
  322. string namespaceURI)
  323. {
  324. string prefix = null;
  325. string localName = name;
  326. if ((type == XmlNodeType.Attribute) || (type == XmlNodeType.Element) || (type == XmlNodeType.EntityReference))
  327. ParseName (name, out prefix, out localName);
  328. return CreateNode (type, prefix, localName, namespaceURI);
  329. }
  330. public virtual XmlNode CreateNode (
  331. XmlNodeType type,
  332. string prefix,
  333. string name,
  334. string namespaceURI)
  335. {
  336. switch (type) {
  337. case XmlNodeType.Attribute: return CreateAttribute (prefix, name, namespaceURI);
  338. case XmlNodeType.CDATA: return CreateCDataSection (null);
  339. case XmlNodeType.Comment: return CreateComment (null);
  340. case XmlNodeType.Document: return new XmlDocument ();
  341. case XmlNodeType.DocumentFragment: return CreateDocumentFragment ();
  342. case XmlNodeType.DocumentType: return CreateDocumentType (null, null, null, null);
  343. case XmlNodeType.Element: return CreateElement (prefix, name, namespaceURI);
  344. case XmlNodeType.EntityReference: return CreateEntityReference (null);
  345. case XmlNodeType.ProcessingInstruction: return CreateProcessingInstruction (null, null);
  346. case XmlNodeType.SignificantWhitespace: return CreateSignificantWhitespace (String.Empty);
  347. case XmlNodeType.Text: return CreateTextNode (null);
  348. case XmlNodeType.Whitespace: return CreateWhitespace (String.Empty);
  349. case XmlNodeType.XmlDeclaration: return CreateXmlDeclaration ("1.0", null, null);
  350. default: throw new ArgumentOutOfRangeException(String.Format("{0}\nParameter name: {1}",
  351. "Specified argument was out of the range of valid values", type.ToString ()));
  352. }
  353. }
  354. public virtual XmlProcessingInstruction CreateProcessingInstruction (
  355. string target,
  356. string data)
  357. {
  358. return new XmlProcessingInstruction (target, data, this);
  359. }
  360. public virtual XmlSignificantWhitespace CreateSignificantWhitespace (string text)
  361. {
  362. if (!XmlChar.IsWhitespace (text))
  363. throw new ArgumentException ("Invalid whitespace characters.");
  364. return new XmlSignificantWhitespace (text, this);
  365. }
  366. public virtual XmlText CreateTextNode (string text)
  367. {
  368. return new XmlText (text, this);
  369. }
  370. public virtual XmlWhitespace CreateWhitespace (string text)
  371. {
  372. if (!XmlChar.IsWhitespace (text))
  373. throw new ArgumentException ("Invalid whitespace characters.");
  374. return new XmlWhitespace (text, this);
  375. }
  376. public virtual XmlDeclaration CreateXmlDeclaration (string version, string encoding,
  377. string standalone)
  378. {
  379. if (version != "1.0")
  380. throw new ArgumentException ("version string is not correct.");
  381. if ((standalone != null && standalone != String.Empty) && !((standalone == "yes") || (standalone == "no")))
  382. throw new ArgumentException ("standalone string is not correct.");
  383. return new XmlDeclaration (version, encoding, standalone, this);
  384. }
  385. // FIXME: Currently XmlAttributeCollection.SetNamedItem() does
  386. // add to the identity table, but in fact I delayed identity
  387. // check on GetIdenticalAttribute. To make such way complete,
  388. // we have to use MultiMap, not Hashtable.
  389. //
  390. // Well, MS.NET is also fragile around here.
  391. public virtual XmlElement GetElementById (string elementId)
  392. {
  393. XmlAttribute attr = GetIdenticalAttribute (elementId);
  394. return attr != null ? attr.OwnerElement : null;
  395. }
  396. public virtual XmlNodeList GetElementsByTagName (string name)
  397. {
  398. ArrayList nodeArrayList = new ArrayList ();
  399. this.SearchDescendantElements (name, name == "*", nodeArrayList);
  400. return new XmlNodeArrayList (nodeArrayList);
  401. }
  402. public virtual XmlNodeList GetElementsByTagName (string localName, string namespaceURI)
  403. {
  404. ArrayList nodeArrayList = new ArrayList ();
  405. this.SearchDescendantElements (localName, localName == "*", namespaceURI, namespaceURI == "*", nodeArrayList);
  406. return new XmlNodeArrayList (nodeArrayList);
  407. }
  408. private XmlNodeType GetNodeTypeFromString (string nodeTypeString)
  409. {
  410. switch (nodeTypeString) {
  411. case "attribute": return XmlNodeType.Attribute;
  412. case "cdatasection": return XmlNodeType.CDATA;
  413. case "comment": return XmlNodeType.Comment;
  414. case "document": return XmlNodeType.Document;
  415. case "documentfragment": return XmlNodeType.DocumentFragment;
  416. case "documenttype": return XmlNodeType.DocumentType;
  417. case "element": return XmlNodeType.Element;
  418. case "entityreference": return XmlNodeType.EntityReference;
  419. case "processinginstruction": return XmlNodeType.ProcessingInstruction;
  420. case "significantwhitespace": return XmlNodeType.SignificantWhitespace;
  421. case "text": return XmlNodeType.Text;
  422. case "whitespace": return XmlNodeType.Whitespace;
  423. default:
  424. throw new ArgumentException(String.Format("The string doesn't represent any node type : {0}.", nodeTypeString));
  425. }
  426. }
  427. internal XmlAttribute GetIdenticalAttribute (string id)
  428. {
  429. XmlAttribute attr = this.idTable [id] as XmlAttribute;
  430. if (attr == null)
  431. return null;
  432. if (attr.OwnerElement == null || !attr.OwnerElement.IsRooted) {
  433. // idTable.Remove (id);
  434. return null;
  435. }
  436. return attr;
  437. }
  438. public virtual XmlNode ImportNode (XmlNode node, bool deep)
  439. {
  440. if (node == null)
  441. throw new NullReferenceException ("Null node cannot be imported.");
  442. switch (node.NodeType) {
  443. case XmlNodeType.Attribute:
  444. XmlAttribute srcAtt = node as XmlAttribute;
  445. XmlAttribute dstAtt = this.CreateAttribute (srcAtt.Prefix, srcAtt.LocalName, srcAtt.NamespaceURI);
  446. for (int i = 0; i < srcAtt.ChildNodes.Count; i++)
  447. dstAtt.AppendChild (this.ImportNode (srcAtt.ChildNodes [i], deep));
  448. return dstAtt;
  449. case XmlNodeType.CDATA:
  450. return this.CreateCDataSection (node.Value);
  451. case XmlNodeType.Comment:
  452. return this.CreateComment (node.Value);
  453. case XmlNodeType.Document:
  454. throw new XmlException ("Document cannot be imported.");
  455. case XmlNodeType.DocumentFragment:
  456. XmlDocumentFragment df = this.CreateDocumentFragment ();
  457. if(deep)
  458. for (int i = 0; i < node.ChildNodes.Count; i++)
  459. df.AppendChild (this.ImportNode (node.ChildNodes [i], deep));
  460. return df;
  461. case XmlNodeType.DocumentType:
  462. throw new XmlException ("DocumentType cannot be imported.");
  463. case XmlNodeType.Element:
  464. XmlElement src = (XmlElement)node;
  465. XmlElement dst = this.CreateElement (src.Prefix, src.LocalName, src.NamespaceURI);
  466. for (int i = 0; i < src.Attributes.Count; i++) {
  467. XmlAttribute attr = src.Attributes [i];
  468. if(attr.Specified) // copies only specified attributes
  469. dst.SetAttributeNode ((XmlAttribute) this.ImportNode (attr, deep));
  470. }
  471. if(deep)
  472. for (int i = 0; i < src.ChildNodes.Count; i++)
  473. dst.AppendChild (this.ImportNode (src.ChildNodes [i], deep));
  474. return dst;
  475. case XmlNodeType.EndElement:
  476. throw new XmlException ("Illegal ImportNode call for NodeType.EndElement");
  477. case XmlNodeType.EndEntity:
  478. throw new XmlException ("Illegal ImportNode call for NodeType.EndEntity");
  479. case XmlNodeType.EntityReference:
  480. return this.CreateEntityReference (node.Name);
  481. case XmlNodeType.None:
  482. throw new XmlException ("Illegal ImportNode call for NodeType.None");
  483. case XmlNodeType.ProcessingInstruction:
  484. XmlProcessingInstruction pi = node as XmlProcessingInstruction;
  485. return this.CreateProcessingInstruction (pi.Target, pi.Data);
  486. case XmlNodeType.SignificantWhitespace:
  487. return this.CreateSignificantWhitespace (node.Value);
  488. case XmlNodeType.Text:
  489. return this.CreateTextNode (node.Value);
  490. case XmlNodeType.Whitespace:
  491. return this.CreateWhitespace (node.Value);
  492. case XmlNodeType.XmlDeclaration:
  493. XmlDeclaration srcDecl = node as XmlDeclaration;
  494. return this.CreateXmlDeclaration (srcDecl.Version, srcDecl.Encoding, srcDecl.Standalone);
  495. default:
  496. throw new InvalidOperationException ("Cannot import specified node type: " + node.NodeType);
  497. }
  498. }
  499. public virtual void Load (Stream inStream)
  500. {
  501. XmlTextReader reader = new XmlTextReader (inStream, NameTable);
  502. reader.XmlResolver = resolver;
  503. Load (reader);
  504. }
  505. public virtual void Load (string filename)
  506. {
  507. XmlTextReader xr = null;
  508. try {
  509. xr = new XmlTextReader (filename, NameTable);
  510. xr.XmlResolver = resolver;
  511. Load (xr);
  512. } finally {
  513. if (xr != null)
  514. xr.Close ();
  515. }
  516. }
  517. public virtual void Load (TextReader txtReader)
  518. {
  519. XmlTextReader xr = new XmlTextReader (txtReader, NameTable);
  520. xr.XmlResolver = resolver;
  521. Load (xr);
  522. }
  523. public virtual void Load (XmlReader xmlReader)
  524. {
  525. // Reset our document
  526. // For now this just means removing all our children but later this
  527. // may turn out o need to call a private method that resets other things
  528. // like properties we have, etc.
  529. RemoveAll ();
  530. this.baseURI = xmlReader.BaseURI;
  531. // create all contents with use of ReadNode()
  532. try {
  533. loadMode = true;
  534. do {
  535. XmlNode n = ReadNode (xmlReader);
  536. if (n == null)
  537. break;
  538. if (preserveWhitespace || n.NodeType != XmlNodeType.Whitespace)
  539. AppendChild (n);
  540. } while (true);
  541. #if NET_2_0
  542. if (xmlReader.Settings != null)
  543. schemas = xmlReader.Settings.Schemas;
  544. #endif
  545. } finally {
  546. loadMode = false;
  547. }
  548. }
  549. public virtual void LoadXml (string xml)
  550. {
  551. XmlTextReader xmlReader = new XmlTextReader (
  552. xml,
  553. XmlNodeType.Document,
  554. new XmlParserContext (NameTable, null, null, XmlSpace.None));
  555. try {
  556. xmlReader.XmlResolver = resolver;
  557. Load (xmlReader);
  558. } finally {
  559. xmlReader.Close ();
  560. }
  561. }
  562. internal void onNodeChanged (XmlNode node, XmlNode parent, string oldValue, string newValue)
  563. {
  564. if (NodeChanged != null)
  565. NodeChanged (node, new XmlNodeChangedEventArgs
  566. (XmlNodeChangedAction.Change,
  567. node, parent, oldValue, newValue));
  568. }
  569. internal void onNodeChanging(XmlNode node, XmlNode parent, string oldValue, string newValue)
  570. {
  571. if (node.IsReadOnly)
  572. throw new ArgumentException ("Node is read-only.");
  573. if (NodeChanging != null)
  574. NodeChanging (node, new XmlNodeChangedEventArgs
  575. (XmlNodeChangedAction.Change,
  576. node, parent, oldValue, newValue));
  577. }
  578. internal void onNodeInserted (XmlNode node, XmlNode newParent)
  579. {
  580. if (NodeInserted != null)
  581. NodeInserted (node, new XmlNodeChangedEventArgs
  582. (XmlNodeChangedAction.Insert,
  583. node, null, newParent));
  584. }
  585. internal void onNodeInserting (XmlNode node, XmlNode newParent)
  586. {
  587. if (NodeInserting != null)
  588. NodeInserting (node, new XmlNodeChangedEventArgs
  589. (XmlNodeChangedAction.Insert,
  590. node, null, newParent));
  591. }
  592. internal void onNodeRemoved (XmlNode node, XmlNode oldParent)
  593. {
  594. if (NodeRemoved != null)
  595. NodeRemoved (node, new XmlNodeChangedEventArgs
  596. (XmlNodeChangedAction.Remove,
  597. node, oldParent, null));
  598. }
  599. internal void onNodeRemoving (XmlNode node, XmlNode oldParent)
  600. {
  601. if (NodeRemoving != null)
  602. NodeRemoving (node, new XmlNodeChangedEventArgs
  603. (XmlNodeChangedAction.Remove,
  604. node, oldParent, null));
  605. }
  606. private void ParseName (string name, out string prefix, out string localName)
  607. {
  608. int indexOfColon = name.IndexOf (':');
  609. if (indexOfColon != -1) {
  610. prefix = name.Substring (0, indexOfColon);
  611. localName = name.Substring (indexOfColon + 1);
  612. } else {
  613. prefix = "";
  614. localName = name;
  615. }
  616. }
  617. // Reads XmlReader and creates Attribute Node.
  618. private XmlAttribute ReadAttributeNode (XmlReader reader)
  619. {
  620. if (reader.NodeType == XmlNodeType.Element)
  621. reader.MoveToFirstAttribute ();
  622. else if (reader.NodeType != XmlNodeType.Attribute)
  623. throw new InvalidOperationException (MakeReaderErrorMessage ("bad position to read attribute.", reader));
  624. XmlAttribute attribute = CreateAttribute (reader.Prefix, reader.LocalName, reader.NamespaceURI, false, false); // different NameTable
  625. #if NET_2_0
  626. if (reader.SchemaInfo != null)
  627. SchemaInfo = new XmlSchemaInfo (reader.SchemaInfo);
  628. #endif
  629. ReadAttributeNodeValue (reader, attribute);
  630. // Keep the current reader position on attribute.
  631. if (attribute.NamespaceURI == null)
  632. reader.MoveToAttribute (attribute.Name);
  633. else
  634. reader.MoveToAttribute (attribute.LocalName, attribute.NamespaceURI);
  635. if (reader.IsDefault)
  636. attribute.SetDefault ();
  637. return attribute;
  638. }
  639. // Reads attribute from XmlReader and then creates attribute value children. XmlAttribute also uses this.
  640. internal void ReadAttributeNodeValue (XmlReader reader, XmlAttribute attribute)
  641. {
  642. while (reader.ReadAttributeValue ()) {
  643. if (reader.NodeType == XmlNodeType.EntityReference)
  644. attribute.AppendChild (CreateEntityReference (reader.Name));
  645. else
  646. // Children of Attribute is restricted to CharacterData and EntityReference (Comment is not allowed).
  647. attribute.AppendChild (CreateTextNode (reader.Value));
  648. }
  649. }
  650. [PermissionSet (SecurityAction.InheritanceDemand, Unrestricted = true)]
  651. public virtual XmlNode ReadNode (XmlReader reader)
  652. {
  653. switch (reader.ReadState) {
  654. case ReadState.Interactive:
  655. break;
  656. case ReadState.Initial:
  657. reader.Read ();
  658. break;
  659. default:
  660. return null;
  661. }
  662. XmlNode n;
  663. switch (reader.NodeType) {
  664. case XmlNodeType.Attribute:
  665. return ReadAttributeNode (reader);
  666. case XmlNodeType.CDATA:
  667. n = CreateCDataSection (reader.Value);
  668. break;
  669. case XmlNodeType.Comment:
  670. n = CreateComment (reader.Value);
  671. break;
  672. case XmlNodeType.Element:
  673. XmlElement element = CreateElement (reader.Prefix, reader.LocalName, reader.NamespaceURI);
  674. #if NET_2_0
  675. if (reader.SchemaInfo != null)
  676. SchemaInfo = new XmlSchemaInfo (reader.SchemaInfo);
  677. #endif
  678. element.IsEmpty = reader.IsEmptyElement;
  679. // set the element's attributes.
  680. if (reader.MoveToFirstAttribute ()) {
  681. do {
  682. element.SetAttributeNode (ReadAttributeNode (reader));
  683. } while (reader.MoveToNextAttribute ());
  684. reader.MoveToElement ();
  685. }
  686. int depth = reader.Depth;
  687. if (element.IsEmpty) {
  688. n = element;
  689. break;
  690. }
  691. reader.Read ();
  692. while (reader.Depth > depth) {
  693. n = ReadNode (reader);
  694. if (preserveWhitespace || n.NodeType != XmlNodeType.Whitespace)
  695. element.AppendChild (n);
  696. }
  697. n = element;
  698. break;
  699. case XmlNodeType.ProcessingInstruction:
  700. n = CreateProcessingInstruction (reader.Name, reader.Value);
  701. break;
  702. case XmlNodeType.Text:
  703. n = CreateTextNode (reader.Value);
  704. break;
  705. case XmlNodeType.XmlDeclaration:
  706. n = CreateXmlDeclaration ("1.0" , String.Empty, String.Empty);
  707. n.Value = reader.Value;
  708. break;
  709. case XmlNodeType.DocumentType:
  710. DTDObjectModel dtd = null;
  711. IHasXmlParserContext ctxReader = reader as IHasXmlParserContext;
  712. if (ctxReader != null)
  713. dtd = ctxReader.ParserContext.Dtd;
  714. if (dtd != null)
  715. n = CreateDocumentType (dtd);
  716. else
  717. n = CreateDocumentType (reader.Name, reader ["PUBLIC"], reader ["SYSTEM"], reader.Value);
  718. break;
  719. case XmlNodeType.EntityReference:
  720. if (this.loadMode && this.DocumentType != null &&
  721. DocumentType.Entities.GetNamedItem (reader.Name) == null)
  722. throw new XmlException ("Reference to undeclared entity was found.");
  723. n = CreateEntityReference (reader.Name);
  724. // IF argument XmlReader can resolve entity,
  725. // ReadNode() also fills children _from it_.
  726. // In this case, it is not from doctype node.
  727. // (it is kind of sucky design, but it happens
  728. // anyways when we modify doctype node).
  729. //
  730. // It does not happen when !CanResolveEntity.
  731. // (In such case AppendChild() will resolve
  732. // entity content, as XmlEntityReference does.)
  733. if (reader.CanResolveEntity)
  734. {
  735. reader.ResolveEntity ();
  736. reader.Read ();
  737. for (XmlNode child; reader.NodeType != XmlNodeType.EndEntity && (child = ReadNode (reader)) != null;)
  738. n.InsertBefore (child, null, false, false);
  739. }
  740. break;
  741. case XmlNodeType.SignificantWhitespace:
  742. n = CreateSignificantWhitespace (reader.Value);
  743. break;
  744. case XmlNodeType.Whitespace:
  745. n = CreateWhitespace (reader.Value);
  746. break;
  747. case XmlNodeType.None:
  748. return null;
  749. default:
  750. // No idea why MS does throw NullReferenceException ;-P
  751. throw new NullReferenceException ("Unexpected node type " + reader.NodeType + ".");
  752. }
  753. reader.Read ();
  754. return n;
  755. }
  756. private string MakeReaderErrorMessage (string message, XmlReader reader)
  757. {
  758. IXmlLineInfo li = reader as IXmlLineInfo;
  759. if (li != null)
  760. return String.Format (CultureInfo.InvariantCulture, "{0} Line number = {1}, Inline position = {2}.", message, li.LineNumber, li.LinePosition);
  761. else
  762. return message;
  763. }
  764. internal void RemoveIdenticalAttribute (string id)
  765. {
  766. idTable.Remove (id);
  767. }
  768. public virtual void Save (Stream outStream)
  769. {
  770. XmlTextWriter xmlWriter = new XmlTextWriter (outStream, TextEncoding);
  771. if (!PreserveWhitespace)
  772. xmlWriter.Formatting = Formatting.Indented;
  773. WriteContentTo (xmlWriter);
  774. xmlWriter.Flush ();
  775. }
  776. public virtual void Save (string filename)
  777. {
  778. XmlTextWriter xmlWriter = new XmlTextWriter (filename, TextEncoding);
  779. try {
  780. if (!PreserveWhitespace)
  781. xmlWriter.Formatting = Formatting.Indented;
  782. WriteContentTo (xmlWriter);
  783. } finally {
  784. xmlWriter.Close ();
  785. }
  786. }
  787. public virtual void Save (TextWriter writer)
  788. {
  789. XmlTextWriter xmlWriter = new XmlTextWriter (writer);
  790. if (!PreserveWhitespace)
  791. xmlWriter.Formatting = Formatting.Indented;
  792. if (FirstChild != null && FirstChild.NodeType != XmlNodeType.XmlDeclaration)
  793. xmlWriter.WriteStartDocument ();
  794. WriteContentTo (xmlWriter);
  795. xmlWriter.WriteEndDocument ();
  796. xmlWriter.Flush ();
  797. }
  798. public virtual void Save (XmlWriter xmlWriter)
  799. {
  800. //
  801. // This should preserve white space if PreserveWhiteSpace is true
  802. //
  803. bool autoXmlDecl = FirstChild != null && FirstChild.NodeType != XmlNodeType.XmlDeclaration;
  804. if (autoXmlDecl)
  805. xmlWriter.WriteStartDocument ();
  806. WriteContentTo (xmlWriter);
  807. if (autoXmlDecl)
  808. xmlWriter.WriteEndDocument ();
  809. xmlWriter.Flush ();
  810. }
  811. public override void WriteContentTo (XmlWriter w)
  812. {
  813. for (int i = 0; i < ChildNodes.Count; i++)
  814. ChildNodes [i].WriteTo (w);
  815. }
  816. public override void WriteTo (XmlWriter w)
  817. {
  818. WriteContentTo (w);
  819. }
  820. private void AddDefaultNameTableKeys ()
  821. {
  822. // The following keys are default of MS .NET Framework
  823. nameTable.Add ("#text");
  824. nameTable.Add ("xml");
  825. nameTable.Add ("xmlns");
  826. nameTable.Add ("#entity");
  827. nameTable.Add ("#document-fragment");
  828. nameTable.Add ("#comment");
  829. nameTable.Add ("space");
  830. nameTable.Add ("id");
  831. nameTable.Add ("#whitespace");
  832. nameTable.Add ("http://www.w3.org/2000/xmlns/");
  833. nameTable.Add ("#cdata-section");
  834. nameTable.Add ("lang");
  835. nameTable.Add ("#document");
  836. nameTable.Add ("#significant-whitespace");
  837. }
  838. #if NET_2_0
  839. public void Validate (ValidationEventHandler handler)
  840. {
  841. Validate (handler, this,
  842. XmlSchemaValidationFlags.IgnoreValidationWarnings);
  843. }
  844. public void Validate (ValidationEventHandler handler,
  845. XmlNode node)
  846. {
  847. Validate (handler, node,
  848. XmlSchemaValidationFlags.IgnoreValidationWarnings |
  849. XmlSchemaValidationFlags.IgnoreIdentityConstraints);
  850. }
  851. private void Validate (ValidationEventHandler handler,
  852. XmlNode node, XmlSchemaValidationFlags flags)
  853. {
  854. XmlReaderSettings settings = new XmlReaderSettings ();
  855. settings.NameTable = NameTable;
  856. settings.Schemas = schemas;
  857. settings.Schemas.XmlResolver = resolver;
  858. settings.XmlResolver = resolver;
  859. settings.ValidationFlags = flags;
  860. settings.ValidationType = ValidationType.Schema;
  861. XmlReader r = XmlReader.Create (
  862. new XmlNodeReader (node), settings);
  863. while (!r.EOF)
  864. r.Read ();
  865. }
  866. #endif
  867. #endregion
  868. }
  869. }