XmlUtil.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  1. using System;
  2. using System.Text;
  3. using System.IO;
  4. using System.Xml;
  5. using System.Reflection;
  6. using System.Collections;
  7. using System.Collections.Generic;
  8. using CommonLang.Property;
  9. using CommonLang.IO;
  10. using CommonLang.Log;
  11. using CommonLang.Concurrent;
  12. namespace CommonLang.Xml
  13. {
  14. public enum XmlSerializableProperty : uint
  15. {
  16. Mark = 0,
  17. IgnoreClone = 0x0001,
  18. NoSerialize = 0x0002,
  19. }
  20. /// <summary>
  21. /// 标记当前Field或者Property是否参与Xml序列化
  22. /// </summary>
  23. [AttributeUsage(AttributeTargets.Property)]
  24. public class XmlSerializableAttribute : System.Attribute
  25. {
  26. private readonly XmlSerializableProperty Prop;
  27. public XmlSerializableAttribute(XmlSerializableProperty attr = XmlSerializableProperty.Mark)
  28. {
  29. this.Prop = attr;
  30. }
  31. public bool IgnoreClone { get { return (Prop & XmlSerializableProperty.IgnoreClone) != 0; } }
  32. public bool NoSerialize { get { return (Prop & XmlSerializableProperty.NoSerialize) != 0; } }
  33. }
  34. /// <summary>
  35. /// Xml序列化与反序列化
  36. /// </summary>
  37. public static class XmlUtil
  38. {
  39. private static Logger s_log;
  40. private static Logger log
  41. {
  42. get
  43. {
  44. if (s_log == null) { s_log = LoggerFactory.GetLogger("XmlUtil"); }
  45. return s_log;
  46. }
  47. }
  48. static public XmlDocument LoadXML(byte[] data)
  49. {
  50. using (MemoryStream ms = new MemoryStream(data))
  51. {
  52. return LoadXML(ms);
  53. }
  54. }
  55. static public XmlDocument LoadXML(Stream input, bool autoDisposeStream = false)
  56. {
  57. try
  58. {
  59. using (XmlReader xml = XmlReader.Create(input))
  60. {
  61. XmlDocument doc = new XmlDocument();
  62. doc.Load(xml);
  63. return doc;
  64. }
  65. }
  66. finally
  67. {
  68. if (autoDisposeStream)
  69. {
  70. input.Close();
  71. input.Dispose();
  72. }
  73. }
  74. }
  75. static public XmlDocument LoadXML(string path)
  76. {
  77. var stream = Resource.LoadDataAsStream(path);
  78. if (stream != null)
  79. {
  80. try
  81. {
  82. return LoadXML(stream);
  83. }
  84. finally
  85. {
  86. stream.Dispose();
  87. }
  88. }
  89. return null;
  90. }
  91. static public void SaveXML(string path, XmlDocument xml)
  92. {
  93. using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
  94. {
  95. XmlUtil.SaveXML(fs, xml, false);
  96. }
  97. }
  98. static public string ToString(XmlDocument doc)
  99. {
  100. using (StringWriter sw = new StringWriter())
  101. {
  102. XmlWriterSettings settings = new XmlWriterSettings();
  103. settings.Indent = true;
  104. settings.Encoding = CUtils.UTF8;
  105. using (XmlWriter xml = XmlWriter.Create(sw, settings))
  106. {
  107. doc.Save(xml);
  108. xml.Flush();
  109. }
  110. return sw.ToString();
  111. }
  112. }
  113. static public XmlDocument FromString(string xmltext)
  114. {
  115. XmlDocument doc = new XmlDocument();
  116. doc.LoadXml(xmltext);
  117. return doc;
  118. }
  119. static public void SaveXML(Stream output, XmlDocument doc, bool autoDisposeStream)
  120. {
  121. try
  122. {
  123. XmlWriterSettings settings = new XmlWriterSettings();
  124. settings.Indent = true;
  125. settings.Encoding = Encoding.UTF8;
  126. using (XmlWriter xml = XmlWriter.Create(output, settings))
  127. {
  128. doc.Save(xml);
  129. xml.Flush();
  130. }
  131. }
  132. finally
  133. {
  134. if (autoDisposeStream)
  135. {
  136. output.Close();
  137. output.Dispose();
  138. }
  139. }
  140. }
  141. static public string GetTextValue(XmlElement e)
  142. {
  143. if (e.FirstChild != null && e.FirstChild.NodeType == XmlNodeType.Text)
  144. {
  145. return (e.FirstChild as XmlText).Data;
  146. }
  147. else { return null; }
  148. }
  149. static public void SaveToXML(Stream output, object mData, bool autoDisposeStream = false)
  150. {
  151. try
  152. {
  153. Type type = mData.GetType();
  154. XmlDocument doc = XmlUtil.ObjectToXml(mData);
  155. XmlWriterSettings settings = new XmlWriterSettings();
  156. settings.Indent = true;
  157. settings.Encoding = Encoding.UTF8;
  158. using (XmlWriter xml = XmlWriter.Create(output, settings))
  159. {
  160. doc.Save(xml);
  161. xml.Flush();
  162. }
  163. }
  164. finally
  165. {
  166. if (autoDisposeStream)
  167. {
  168. output.Close();
  169. output.Dispose();
  170. }
  171. }
  172. }
  173. //----------------------------------------------------------------------------------------------------------
  174. #region _converter_
  175. static public T XmlToObject<T>(XmlDocument doc, Action<Exception> error = null)
  176. {
  177. object ret = XmlToObject(typeof(T), doc, false, error);
  178. if (ret != null)
  179. {
  180. return (T)ret;
  181. }
  182. return default(T);
  183. }
  184. static public object XmlToObject(XmlDocument doc, Action<Exception> error = null)
  185. {
  186. XmlElement e = (XmlElement)doc.DocumentElement;
  187. Type type = GetTypeFromAttribute(e, "type");
  188. return XmlToObject(type, doc, false, error);
  189. }
  190. static public object XmlToObject(Type type, XmlDocument doc, Action<Exception> error = null)
  191. {
  192. XmlElement e = (XmlElement)doc.DocumentElement;
  193. return XmlToObject(type, doc, false, error);
  194. }
  195. static public object XmlToObject(Type type, XmlDocument doc, bool cloning, Action<Exception> error = null)
  196. {
  197. XmlElement e = (XmlElement)doc.DocumentElement;
  198. object data = ObjectFromXmlElement(e, type, cloning, error);
  199. return data;
  200. }
  201. static public XmlDocument ObjectToXml(object data, string root_name = null)
  202. {
  203. return ObjectToXml(data, root_name, false);
  204. }
  205. static public XmlDocument ObjectToXml(object data, string root_name, bool cloning)
  206. {
  207. Type type = data.GetType();
  208. if (root_name == null)
  209. {
  210. root_name = type.Name;
  211. }
  212. XmlDocument doc = new XmlDocument();
  213. XmlElement e = doc.CreateElement(root_name);
  214. ObjectToXmlElement(e, data, cloning);
  215. doc.AppendChild(e);
  216. return doc;
  217. }
  218. static public T CloneObject<T>(T src)
  219. {
  220. Type type = src.GetType();
  221. if (type.IsPrimitive)
  222. {
  223. return src;
  224. }
  225. else if (type.IsEnum)
  226. {
  227. return src;
  228. }
  229. else if (type.IsAssignableFrom(typeof(string)))
  230. {
  231. return src;
  232. }
  233. else if (type.IsClass || type.IsArray)
  234. {
  235. XmlDocument xml = XmlUtil.ObjectToXml(src, "cloning", true);
  236. T obj = (T)XmlUtil.XmlToObject(type, xml, true);
  237. return obj;
  238. }
  239. return src;
  240. }
  241. #endregion
  242. //----------------------------------------------------------------------------------------------------------
  243. #region _internal_
  244. static private void ObjectFieldsFromXMLElement(XmlElement data_element, object data, bool cloning, Action<Exception> error)
  245. {
  246. Type type = data.GetType();
  247. foreach (XmlNode fe in data_element.ChildNodes)
  248. {
  249. XmlElement fee = fe as XmlElement;
  250. FieldInfo fii = type.GetField(fe.Name);
  251. if (fii != null)
  252. {
  253. object fd = ObjectFromXmlElement(fee, fii.FieldType, cloning, error);
  254. fii.SetValue(data, fd);
  255. }
  256. }
  257. }
  258. static private void ObjectToXmlElement(XmlElement data_element, object data, bool cloning)
  259. {
  260. if (data != null)
  261. {
  262. Type type = data.GetType();
  263. if (type.IsPrimitive)
  264. {
  265. data_element.InnerText = Parser.ObjectToString(data);
  266. }
  267. else if (type.IsEnum)
  268. {
  269. data_element.InnerText = Parser.ObjectToString(data);
  270. }
  271. else if (type.IsAssignableFrom(typeof(string)))
  272. {
  273. data_element.InnerText = Parser.ObjectToString(data);
  274. }
  275. else if (type.IsArray)
  276. {
  277. ObjectToXMLElementArray(data_element, (Array)data, cloning);
  278. }
  279. else if (type.IsClass)
  280. {
  281. XmlDocument doc = data_element.OwnerDocument;
  282. if (type.GetInterface(typeof(IDictionary).Name) != null)
  283. {
  284. ObjectToXMLElementMap(data_element, (IDictionary)data, cloning);
  285. }
  286. else if (type.GetInterface(typeof(IList).Name) != null)
  287. {
  288. ObjectToXMLElementList(data_element, (IList)data, cloning);
  289. }
  290. else
  291. {
  292. SetTypeToAttribute(data_element, "type", type);
  293. foreach (FieldInfo field in PropertyUtil.SortFields(type.GetFields()))
  294. {
  295. if (!field.IsStatic)
  296. {
  297. object fd = field.GetValue(data);
  298. if (fd != null)
  299. {
  300. XmlElement fe = doc.CreateElement(field.Name);
  301. ObjectToXmlElement(fe, fd, cloning);
  302. data_element.AppendChild(fe);
  303. }
  304. }
  305. }
  306. foreach (PropertyInfo property in PropertyUtil.SortProperties(type.GetProperties()))
  307. {
  308. XmlSerializableAttribute attr = PropertyUtil.GetAttribute<XmlSerializableAttribute>(property);
  309. if (attr != null)
  310. {
  311. if (attr.NoSerialize)
  312. {
  313. }
  314. else if (cloning && attr.IgnoreClone)
  315. {
  316. }
  317. else
  318. {
  319. object fd = property.GetValue(data, null);
  320. if (fd != null)
  321. {
  322. XmlElement fe = doc.CreateElement("property." + property.Name);
  323. ObjectToXmlElement(fe, fd, cloning);
  324. data_element.AppendChild(fe);
  325. }
  326. }
  327. }
  328. }
  329. }
  330. }
  331. }
  332. }
  333. static private object ObjectFromXmlElement(XmlElement data_element, Type type, bool cloning, Action<Exception> error)
  334. {
  335. try
  336. {
  337. Type s_type = GetTypeFromAttribute(data_element, "type", type);
  338. if (s_type != null)
  339. {
  340. type = s_type;
  341. }
  342. if (type.IsPrimitive)
  343. {
  344. return Parser.StringToObject(data_element.InnerText, type);
  345. }
  346. else if (type.IsEnum)
  347. {
  348. return Parser.StringToObject(data_element.InnerText, type);
  349. }
  350. else if (type.IsAssignableFrom(typeof(string)))
  351. {
  352. return data_element.InnerText;
  353. }
  354. else if (type.IsArray)
  355. {
  356. return ObjectFromXMLElementArray(data_element, type, cloning, error);
  357. }
  358. else if (type.IsClass)
  359. {
  360. if (type.GetInterface(typeof(IDictionary).Name) != null)
  361. {
  362. return ObjectFromXMLElementMap(data_element, type, cloning, error);
  363. }
  364. else if (type.GetInterface(typeof(IList).Name) != null)
  365. {
  366. return ObjectFromXMLElementList(data_element, type, cloning, error);
  367. }
  368. else
  369. {
  370. try
  371. {
  372. object data = ReflectionUtil.CreateInstance(type);
  373. foreach (XmlNode fe in data_element.ChildNodes)
  374. {
  375. XmlElement fee = fe as XmlElement;
  376. if (fe.Name.StartsWith("property."))
  377. {
  378. PropertyInfo property = type.GetProperty(fe.Name.Substring("property.".Length));
  379. if (property != null)
  380. {
  381. XmlSerializableAttribute attr = PropertyUtil.GetAttribute<XmlSerializableAttribute>(property);
  382. if (attr != null)
  383. {
  384. if (attr.NoSerialize)
  385. {
  386. }
  387. else if (cloning && attr.IgnoreClone)
  388. {
  389. }
  390. else
  391. {
  392. object fd = ObjectFromXmlElement(fee, property.PropertyType, cloning, error);
  393. if (fd != null)
  394. {
  395. property.SetValue(data, fd, null);
  396. }
  397. }
  398. }
  399. }
  400. }
  401. else
  402. {
  403. FieldInfo fii = type.GetField(fe.Name);
  404. if (fii != null)
  405. {
  406. object fd = ObjectFromXmlElement(fee, fii.FieldType, cloning, error);
  407. if (fd != null)
  408. {
  409. fii.SetValue(data, fd);
  410. }
  411. }
  412. }
  413. }
  414. return data;
  415. }
  416. catch (Exception err)
  417. {
  418. log.Warn(err.Message, err);
  419. if (error != null) error(err);
  420. }
  421. }
  422. }
  423. }
  424. catch (Exception err)
  425. {
  426. log.Warn(err.Message, err);
  427. if (error != null) error(err);
  428. }
  429. return null;
  430. }
  431. static private void ObjectToXMLElementArray(XmlElement data_element, Array array, bool cloning)
  432. {
  433. XmlDocument doc = data_element.OwnerDocument;
  434. Type type = array.GetType();
  435. int rank = type.GetArrayRank();
  436. int[] ranges = new int[rank];
  437. for (int i = 0; i < rank; i++)
  438. {
  439. ranges[i] = array.GetLength(i);
  440. }
  441. SetTypeToAttribute(data_element, "type", type);
  442. SetTypeToAttribute(data_element, "element_type", type.GetElementType());
  443. data_element.SetAttribute("rank", rank + "");
  444. data_element.SetAttribute("ranges", Parser.ObjectToString(ranges));
  445. foreach (object k in array)
  446. {
  447. XmlElement ei = doc.CreateElement("element");
  448. ObjectToXmlElement(ei, k, cloning);
  449. data_element.AppendChild(ei);
  450. }
  451. }
  452. static private Array ObjectFromXMLElementArray(XmlElement data_element, Type type, bool cloning, Action<Exception> error)
  453. {
  454. int rank = int.Parse(data_element.GetAttribute("rank"));
  455. Type ctype = GetTypeFromAttribute(data_element, "type");
  456. Type etype = GetTypeFromAttribute(data_element, "element_type");
  457. int[] ranges = (int[])Parser.StringToObject(data_element.GetAttribute("ranges"), typeof(int[]));
  458. Array array = Array.CreateInstance(etype, ranges);
  459. int total_index = 0;
  460. foreach (XmlNode fe in data_element.ChildNodes)
  461. {
  462. XmlElement fee = fe as XmlElement;
  463. object fdd = ObjectFromXmlElement(fee, etype, cloning, error);
  464. int[] indices = CUtils.GetArrayRankIndex(ranges, total_index);
  465. array.SetValue(fdd, indices);
  466. total_index++;
  467. }
  468. return array;
  469. }
  470. static private void ObjectToXMLElementMap(XmlElement data_element, IDictionary map, bool cloning)
  471. {
  472. XmlDocument doc = data_element.OwnerDocument;
  473. Type type = map.GetType();
  474. if (type.IsGenericType)
  475. {
  476. SetTypeToAttribute(data_element, "key_type", type.GetGenericArguments()[0]);
  477. SetTypeToAttribute(data_element, "value_type", type.GetGenericArguments()[1]);
  478. }
  479. foreach (object k in map.Keys)
  480. {
  481. object v = map[k];
  482. XmlElement epair = doc.CreateElement("element");
  483. XmlElement ek = doc.CreateElement("key");
  484. XmlElement ev = doc.CreateElement("value");
  485. if (!type.IsGenericType)
  486. {
  487. SetTypeToAttribute(ek, "type", k.GetType());
  488. SetTypeToAttribute(ev, "type", v.GetType());
  489. }
  490. ObjectToXmlElement(ek, k, cloning);
  491. ObjectToXmlElement(ev, v, cloning);
  492. epair.AppendChild(ek);
  493. epair.AppendChild(ev);
  494. data_element.AppendChild(epair);
  495. }
  496. }
  497. static private IDictionary ObjectFromXMLElementMap(XmlElement data_element, Type type, bool cloning, Action<Exception> error)
  498. {
  499. Type k_type = GetTypeFromAttribute(data_element, "key_type");
  500. Type v_type = GetTypeFromAttribute(data_element, "value_type");
  501. IDictionary map = (IDictionary)Activator.CreateInstance(type);
  502. foreach (XmlNode fe in data_element.ChildNodes)
  503. {
  504. XmlElement epair = fe as XmlElement;
  505. XmlElement ek = epair.ChildNodes[0] as XmlElement;
  506. XmlElement ev = epair.ChildNodes[1] as XmlElement;
  507. k_type = GetTypeFromAttribute(ek, "type", k_type);
  508. v_type = GetTypeFromAttribute(ev, "type", v_type);
  509. object k = ObjectFromXmlElement(ek, k_type, cloning, error);
  510. object v = ObjectFromXmlElement(ev, v_type, cloning, error);
  511. map.Add(k, v);
  512. }
  513. return map;
  514. }
  515. static private void ObjectToXMLElementList(XmlElement data_element, IList list, bool cloning)
  516. {
  517. XmlDocument doc = data_element.OwnerDocument;
  518. Type type = list.GetType();
  519. if (type.IsGenericType)
  520. {
  521. SetTypeToAttribute(data_element, "element_type", type.GetGenericArguments()[0]);
  522. }
  523. foreach (object k in list)
  524. {
  525. XmlElement ei = doc.CreateElement("element");
  526. if (!type.IsGenericType)
  527. {
  528. SetTypeToAttribute(ei, "type", k.GetType());
  529. }
  530. ObjectToXmlElement(ei, k, cloning);
  531. data_element.AppendChild(ei);
  532. }
  533. }
  534. static private IList ObjectFromXMLElementList(XmlElement data_element, Type type, bool cloning, Action<Exception> error)
  535. {
  536. Type element_type = GetTypeFromAttribute(data_element, "element_type");
  537. IList list = (IList)Activator.CreateInstance(type);
  538. foreach (XmlNode fe in data_element.ChildNodes)
  539. {
  540. XmlElement ei = fe as XmlElement;
  541. element_type = GetTypeFromAttribute(ei, "type", element_type);
  542. Object fd = ObjectFromXmlElement(ei, element_type, cloning, error);
  543. list.Add(fd);
  544. }
  545. return list;
  546. }
  547. static private void SetTypeToAttribute(XmlElement e, string name, Type type)
  548. {
  549. e.SetAttribute(name, type.FullName);
  550. }
  551. static private Type GetTypeFromAttribute(XmlElement e, string name)
  552. {
  553. string vtype = e.GetAttribute(name);
  554. if (vtype != null)
  555. {
  556. Type ret = ReflectionUtil.GetType(vtype);
  557. if (ret != null)
  558. {
  559. return ret;
  560. }
  561. }
  562. return null;
  563. }
  564. static private Type GetTypeFromAttribute(XmlElement e, string name, Type defaultType)
  565. {
  566. string vtype = e.GetAttribute(name);
  567. if (!String.IsNullOrEmpty(vtype))
  568. {
  569. Type ret = ReflectionUtil.GetType(vtype);
  570. if (ret != null)
  571. {
  572. return ret;
  573. }
  574. }
  575. return defaultType;
  576. }
  577. #endregion
  578. //----------------------------------------------------------------------------------------------------------
  579. #region _utils_
  580. public static bool TryGetAttribute(XmlNode e, string key, out string value, bool NotNull = true)
  581. {
  582. XmlAttribute attr = e.Attributes[key];
  583. if (attr != null)
  584. {
  585. if (NotNull && string.IsNullOrEmpty(attr.Value))
  586. {
  587. value = null;
  588. return false;
  589. }
  590. value = attr.Value;
  591. return true;
  592. }
  593. value = null;
  594. return false;
  595. }
  596. public static string GetAttribute(XmlNode e, string key, bool NotNull = true)
  597. {
  598. XmlAttribute attr = e.Attributes[key];
  599. if (attr != null)
  600. {
  601. if (NotNull && string.IsNullOrEmpty(attr.Value))
  602. {
  603. return null;
  604. }
  605. return attr.Value;
  606. }
  607. return null;
  608. }
  609. public static XmlNode FindChild(XmlNode e, string childName)
  610. {
  611. foreach (XmlNode cc in e.ChildNodes)
  612. {
  613. if (cc.Name == childName)
  614. {
  615. return cc;
  616. }
  617. }
  618. return null;
  619. }
  620. #endregion
  621. //----------------------------------------------------------------------------------------------------
  622. }
  623. }