XMLoperate.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Xml;
  7. namespace OTSIncAReportApp.DataOperation.DataAccess
  8. {
  9. public class XMLoperate
  10. {
  11. #region 读取XML到DataSet
  12. /// <summary>
  13. /// 功能:读取XML到DataSet中
  14. /// </summary>
  15. /// <param name="XmlPath">xml路径</param>
  16. /// <returns>DataSet</returns>
  17. public static DataSet GetXml(string XmlPath)
  18. {
  19. DataSet ds = new DataSet();
  20. ds.ReadXml(@XmlPath);
  21. return ds;
  22. }
  23. #endregion
  24. #region 读取xml文档并返回一个节点
  25. /// <summary>
  26. /// 读取xml文档并返回一个节点:适用于一级节点
  27. /// </summary>
  28. /// <param name="XmlPath">xml路径</param>
  29. /// <param name="NodeName">节点</param>
  30. /// <returns></returns>
  31. public static string ReadXmlReturnNode(string XmlPath, string Node)
  32. {
  33. XmlDocument docXml = new XmlDocument();
  34. docXml.Load(@XmlPath);
  35. XmlNodeList xn = docXml.GetElementsByTagName(Node);
  36. return xn.Item(0).InnerText.ToString();
  37. }
  38. #endregion
  39. #region 查找数据,返回一个DataSet
  40. /// <summary>
  41. /// 查找数据,返回当前节点的所有下级节点,填充到一个DataSet中
  42. /// </summary>
  43. /// <param name="xmlPath">xml文档路径</param>
  44. /// <param name="XmlPathNode">节点的路径:根节点/父节点/当前节点</param>
  45. /// <returns></returns>
  46. public static DataSet GetXmlData(string xmlPath, string XmlPathNode)
  47. {
  48. XmlDocument objXmlDoc = new XmlDocument();
  49. objXmlDoc.Load(xmlPath);
  50. DataSet ds = new DataSet();
  51. StringReader read = new StringReader(objXmlDoc.SelectSingleNode(XmlPathNode).OuterXml);
  52. ds.ReadXml(read);
  53. return ds;
  54. }
  55. #endregion
  56. //必须创建对象才能使用的类
  57. private bool _alreadyDispose = false;
  58. private XmlDocument xmlDoc = new XmlDocument();
  59. private XmlNode xmlNode;
  60. private XmlElement xmlElem;
  61. private string _xmlPath;
  62. #region 构造与释构
  63. public XMLoperate()
  64. {
  65. }
  66. public XMLoperate(string xmlPath)
  67. {
  68. _xmlPath = xmlPath;
  69. }
  70. ~XMLoperate()
  71. {
  72. Dispose();
  73. }
  74. protected virtual void Dispose(bool isDisposing)
  75. {
  76. if (_alreadyDispose) return;
  77. if (isDisposing)
  78. {
  79. //
  80. }
  81. _alreadyDispose = true;
  82. }
  83. #endregion
  84. #region IDisposable 成员
  85. public void Dispose()
  86. {
  87. Dispose(true);
  88. GC.SuppressFinalize(this);
  89. }
  90. #endregion
  91. #region 根据父节点属性值读取子节点值
  92. /// <summary>
  93. /// 根据父节点属性读取字节点值
  94. /// </summary>
  95. /// <param name="XmlPath">xml路径</param>
  96. /// <param name="FatherElenetName">父节点名</param>
  97. /// <param name="AttributeName">属性值</param>
  98. /// <param name="AttributeIndex">属性索引</param>
  99. /// <param name="ArrayLength">要返回的节点数组长度</param>
  100. /// <returns></returns>
  101. public static System.Collections.ArrayList GetSubElementByAttribute(string XmlPath, string FatherElenetName, string AttributeName, int AttributeIndex, int ArrayLength)
  102. {
  103. System.Collections.ArrayList al = new System.Collections.ArrayList();
  104. XmlDocument docXml = new XmlDocument();
  105. docXml.Load(@XmlPath);
  106. XmlNodeList xn = docXml.DocumentElement.ChildNodes;
  107. //遍历第一层节点
  108. foreach (XmlElement element in xn)
  109. {
  110. //判断父节点是否为指定节点
  111. if (element.Name == FatherElenetName)
  112. {
  113. //判断父节点属性的索引是否大于指定索引
  114. if (element.Attributes.Count < AttributeIndex)
  115. return null;
  116. //判断父节点的属性值是否等于指定属性
  117. if (element.Attributes[AttributeIndex].Value == AttributeName)
  118. {
  119. XmlNodeList xx = element.ChildNodes;
  120. if (xx.Count > 0)
  121. {
  122. for (int i = 0; i < ArrayLength & i < xx.Count; i++)
  123. {
  124. al.Add(xx[i].InnerText);
  125. }
  126. }
  127. }
  128. }
  129. }
  130. return al;
  131. }
  132. #endregion
  133. #region 根据节点属性读取子节点值(较省资源模式)
  134. /// <summary>
  135. /// 根据节点属性读取子节点值(较省资源模式)
  136. /// </summary>
  137. /// <param name="XmlPath">xml路径</param>
  138. /// <param name="FatherElement">父节点值</param>
  139. /// <param name="AttributeName">属性名称</param>
  140. /// <param name="AttributeValue">属性值</param>
  141. /// <param name="ArrayLength">返回的数组长度</param>
  142. /// <returns></returns>
  143. public static System.Collections.ArrayList GetSubElementByAttribute(string XmlPath, string FatherElement, string AttributeName, string AttributeValue, int ArrayLength)
  144. {
  145. System.Collections.ArrayList al = new System.Collections.ArrayList();
  146. XmlDocument docXml = new XmlDocument();
  147. docXml.Load(@XmlPath);
  148. XmlNodeList xn;
  149. xn = docXml.DocumentElement.SelectNodes("//" + FatherElement + "[" + @AttributeName + "='" + AttributeValue + "']");
  150. XmlNodeList xx = xn.Item(0).ChildNodes;
  151. for (int i = 0; i < ArrayLength & i < xx.Count; i++)
  152. {
  153. al.Add(xx.Item(i).InnerText);
  154. }
  155. return al;
  156. }
  157. #endregion
  158. #region 根据父节点属性值读取子节点值
  159. /// <summary>
  160. /// 根据父节点属性读取字节点值
  161. /// </summary>
  162. /// <param name="XmlPath">xml路径</param>
  163. /// <returns></returns>
  164. public static Dictionary<string, object> GetXMLAllInfo(string XmlPath)
  165. {
  166. if (XmlPath == "")
  167. {
  168. return null;
  169. }
  170. Dictionary<string, object> suggestions = new Dictionary<string, object>();
  171. XmlDocument docXml = new XmlDocument();
  172. docXml.Load(@XmlPath);
  173. XmlNodeList xn = docXml.DocumentElement.ChildNodes;
  174. //遍历第一层节点
  175. foreach (XmlElement element in xn)
  176. {
  177. string name = element.Name;
  178. if ("Collection"!= name)
  179. {
  180. int attributes = element.Attributes.Count;
  181. Dictionary<string, object> obj = new Dictionary<string, object>();
  182. string key = "";
  183. foreach (System.Xml.XmlAttribute item in element.Attributes)
  184. {
  185. if (item.Name == "RegName")
  186. {
  187. key = item.Value;
  188. }
  189. else
  190. {
  191. obj.Add(item.Name, item.Value);
  192. }
  193. }
  194. if (element.ChildNodes.Count > 0)
  195. {
  196. Dictionary<string, object> childList = GetChildInfo(element.ChildNodes);
  197. if (childList.Count > 0)
  198. {
  199. obj.Add("Members", childList);
  200. }
  201. }
  202. suggestions.Add(key, obj);
  203. }
  204. }
  205. return suggestions;
  206. }
  207. private static Dictionary<string, object> GetChildInfo(XmlNodeList childs)
  208. {
  209. Dictionary<string, object> child = new Dictionary<string, object>();
  210. foreach (XmlElement element in childs)
  211. {
  212. if (element.Name != "Member")
  213. continue;
  214. int attributes = element.Attributes.Count;
  215. Dictionary<string, object> obj = new Dictionary<string, object>();
  216. string key = "";
  217. foreach (System.Xml.XmlAttribute item in element.Attributes)
  218. {
  219. if (item.Name == "RegName")
  220. {
  221. key = item.Value;
  222. }
  223. else
  224. {
  225. obj.Add(item.Name, item.Value);
  226. }
  227. }
  228. if (element.ChildNodes.Count > 0)
  229. {
  230. Dictionary<string, object> childList = GetChildInfo(element.ChildNodes);
  231. if (childList.Count > 0)
  232. {
  233. obj.Add("Members", childList);
  234. }
  235. }
  236. child.Add(key, obj);
  237. }
  238. return child;
  239. }
  240. #endregion
  241. public static List<string> GetMember(string XmlPath, string tem)
  242. {
  243. if (XmlPath == "")
  244. {
  245. return null;
  246. }
  247. XmlDocument docXml = new XmlDocument();
  248. docXml.Load(@XmlPath);
  249. XmlNodeList xn = docXml.DocumentElement.ChildNodes[0].ChildNodes;
  250. List<string> elem = new List<string>();
  251. //遍历第一层节点
  252. foreach (XmlElement element in xn)
  253. {
  254. foreach (System.Xml.XmlAttribute item in element.Attributes)
  255. {
  256. if (item.Name == "TemplateName" && item.Value == tem)
  257. {
  258. elem.Add(element.ChildNodes[0].ChildNodes[0].Attributes["ElementName"].Value);
  259. elem.Add(element.ChildNodes[0].ChildNodes[1].Attributes["ElementName"].Value);
  260. elem.Add(element.ChildNodes[0].ChildNodes[2].Attributes["ElementName"].Value);
  261. return elem;
  262. }
  263. }
  264. }
  265. return elem;
  266. }
  267. /// <summary>
  268. /// 修改xml
  269. /// </summary>
  270. /// <param name="FilePath">文件地址</param>
  271. /// <param name="RegName">节点名称</param>
  272. /// <param name="Name">节点属性名称</param>
  273. /// <param name="Value">节点属性值</param>
  274. public static bool EditXmlInfo(string FilePath, string TagName, string Name, string Value)
  275. {
  276. try
  277. {
  278. XmlDocument xmlDoc = new XmlDocument();
  279. xmlDoc.Load(FilePath); //加载Xml文件
  280. XmlNodeList nodeList = xmlDoc.GetElementsByTagName(TagName);
  281. foreach (XmlNode node in nodeList)
  282. {
  283. XmlElement ele = (XmlElement)node;
  284. ele.SetAttribute(Name, Value);
  285. }
  286. xmlDoc.Save(FilePath);
  287. return true;
  288. }
  289. catch (Exception e)
  290. {
  291. return false;
  292. }
  293. }
  294. /// <summary>
  295. /// 获取XML节点参数
  296. /// </summary>
  297. /// <param name="Name">节点参数名称</param>
  298. /// <returns>节点参数</returns>
  299. public static string GetXMLInformations(string xmlFilePath, string Name)
  300. {
  301. try
  302. {
  303. string value = string.Empty;
  304. XmlDocument doc = new XmlDocument();
  305. doc.Load(xmlFilePath); //加载Xml文件
  306. XmlElement root = doc.DocumentElement; //获取根节点
  307. XmlNodeList mainNodes = root.GetElementsByTagName("parameter"); //获取子节点集合
  308. foreach (XmlNode node in mainNodes)
  309. {
  310. //获取Name属性值
  311. string name = ((XmlElement)node).GetAttribute("Name");
  312. if (name.Equals(Name))
  313. {
  314. value = ((XmlElement)node).GetAttribute("Value");
  315. }
  316. }
  317. return value;
  318. }
  319. catch (Exception)
  320. {
  321. return "";
  322. }
  323. }
  324. /// <summary>
  325. /// 修改第二层节点数据
  326. /// </summary>
  327. /// <param name="XmlPath">XML路径</param>
  328. /// <param name="AttributeName">所有需要修改的属性名称</param>
  329. /// <param name="Value">需要修改的值</param>
  330. /// <returns></returns>
  331. public static bool UpdateByAttribute(string XmlPath, string[] AttributeName, string[] Value)
  332. {
  333. try
  334. {
  335. XmlDocument docXml = new XmlDocument();
  336. docXml.Load(@XmlPath);
  337. XmlNodeList xn = docXml.DocumentElement.ChildNodes;
  338. //遍历第一层节点
  339. foreach (XmlElement element in xn)
  340. {
  341. if (element.Attributes[0].Value == Value[0])
  342. {
  343. for (int i = 0; i < element.Attributes.Count; i++)
  344. {
  345. for (int j = 0; j < AttributeName.Count(); j++)
  346. {
  347. //判断父节点的属性值是否等于指定属性
  348. if (element.Attributes[i].Name == AttributeName[j])
  349. {
  350. element.SetAttribute(AttributeName[j], Value[j]);
  351. break;
  352. }
  353. }
  354. }
  355. break;
  356. }
  357. }
  358. docXml.Save(@XmlPath);
  359. return true;
  360. }
  361. catch (Exception e)
  362. {
  363. return false;
  364. }
  365. }
  366. public static int InsertAttribute(string XmlPath, string[] AttributeName, string[] Value, string nodeName)
  367. {
  368. try
  369. {
  370. XmlDocument docXml = new XmlDocument();
  371. docXml.Load(@XmlPath);
  372. XmlNodeList xn = docXml.DocumentElement.ChildNodes;
  373. foreach (XmlElement element in xn)
  374. {
  375. if (element.Attributes[0].Value == Value[0])
  376. {
  377. return -1;
  378. }
  379. }
  380. XmlElement xe = docXml.CreateElement(nodeName);
  381. for (int i = 0; i < AttributeName.Count(); i++)
  382. {
  383. xe.SetAttribute(AttributeName[i], Value[i]);
  384. }
  385. docXml.DocumentElement.AppendChild(xe);
  386. docXml.Save(@XmlPath);
  387. return 1;
  388. }
  389. catch (Exception e)
  390. {
  391. return 0;
  392. }
  393. }
  394. public static int DeleteByAttribute(string XmlPath, string AttributeName, string Value)
  395. {
  396. try
  397. {
  398. XmlDocument docXml = new XmlDocument();
  399. docXml.Load(@XmlPath);
  400. XmlNodeList xn = docXml.DocumentElement.ChildNodes;
  401. foreach (XmlElement element in xn)
  402. {
  403. if (element.Attributes[AttributeName].Value == Value)
  404. {
  405. element.ParentNode.RemoveChild(element);
  406. docXml.Save(@XmlPath);
  407. return 1;
  408. }
  409. }
  410. return 2;
  411. }
  412. catch (Exception e)
  413. {
  414. return 0;
  415. }
  416. }
  417. #region 报告模板
  418. /// <summary>
  419. /// 写入配置,也可以用来修改
  420. /// </summary>
  421. /// <param name="value">写入的值</param>
  422. /// <param name="nodes">节点</param>
  423. public void Write(string value, params string[] nodes)
  424. {
  425. //初始化xml
  426. XmlDocument xmlDoc = new XmlDocument();
  427. if (File.Exists(_xmlPath))
  428. xmlDoc.Load(_xmlPath);
  429. else
  430. xmlDoc.LoadXml("<XmlConfig />");
  431. XmlNode xmlRoot = xmlDoc.ChildNodes[0];
  432. //新增、编辑 节点
  433. string xpath = string.Join("/", nodes);
  434. XmlNode node = xmlDoc.SelectSingleNode(xpath);
  435. if (node == null) //新增节点
  436. {
  437. node = makeXPath(xmlDoc, xmlRoot, xpath);
  438. }
  439. node.InnerText = value;
  440. //保存
  441. xmlDoc.Save(_xmlPath);
  442. }
  443. /// <summary>
  444. /// 设置节点上属性的值
  445. /// </summary>
  446. /// <param name="AttributeName">属性名</param>
  447. /// <param name="AttributeValue">属性值</param>
  448. /// <param name="nodes">选择节点</param>
  449. public void SetAttribute(string AttributeName, string AttributeValue, params string[] nodes)
  450. {
  451. //初始化xml
  452. XmlDocument xmlDoc = new XmlDocument();
  453. if (File.Exists(_xmlPath))
  454. xmlDoc.Load(_xmlPath);
  455. else
  456. xmlDoc.LoadXml("<XmlConfig />");
  457. XmlNode xmlRoot = xmlDoc.ChildNodes[0];
  458. //新增、编辑 节点
  459. string xpath = string.Join("/", nodes);
  460. XmlElement element = (XmlElement)xmlDoc.SelectSingleNode(xpath);
  461. if (element == null) //新增节点
  462. {
  463. element = (XmlElement)makeXPath(xmlDoc, xmlRoot, xpath);
  464. }
  465. //设置节点上属性的值
  466. element.SetAttribute(AttributeName, AttributeValue);
  467. //保存
  468. xmlDoc.Save(_xmlPath);
  469. }
  470. public string GetAttribute(string AttributeName, params string[] nodes)
  471. {
  472. //初始化xml
  473. XmlDocument xmlDoc = new XmlDocument();
  474. if (File.Exists(_xmlPath))
  475. xmlDoc.Load(_xmlPath);
  476. else
  477. xmlDoc.LoadXml("<XmlConfig />");
  478. XmlNode xmlRoot = xmlDoc.ChildNodes[0];
  479. //新增、编辑 节点
  480. string xpath = string.Join("/", nodes);
  481. XmlElement element = (XmlElement)xmlDoc.SelectSingleNode(xpath);
  482. if (element == null) //新增节点
  483. {
  484. element = (XmlElement)makeXPath(xmlDoc, xmlRoot, xpath);
  485. }
  486. //设置节点上属性的值
  487. string retstr = element.GetAttribute(AttributeName);
  488. //保存
  489. xmlDoc.Save(_xmlPath);
  490. return retstr;
  491. }
  492. /// <summary>
  493. /// 读取配置
  494. /// </summary>
  495. /// <param name="nodes">节点</param>
  496. /// <returns></returns>
  497. public string Read(params string[] nodes)
  498. {
  499. XmlDocument xmlDoc = new XmlDocument();
  500. if (File.Exists(_xmlPath) == false)
  501. return null;
  502. else
  503. xmlDoc.Load(_xmlPath);
  504. string xpath = string.Join("/", nodes);
  505. XmlNode node = xmlDoc.SelectSingleNode("/XmlConfig/" + xpath);
  506. if (node == null)
  507. return null;
  508. return node.InnerText;
  509. }
  510. /// <summary>
  511. /// 删除节点
  512. /// </summary>
  513. /// <param name="nodes"></param>
  514. public void RemoveNode(params string[] nodes)
  515. {
  516. XmlDocument xmlDoc = new XmlDocument();
  517. if (File.Exists(_xmlPath) == false)
  518. return;
  519. else
  520. xmlDoc.Load(_xmlPath);
  521. string xpath = string.Join("/", nodes);
  522. XmlNode node = xmlDoc.SelectSingleNode("/XmlConfig/" + xpath);
  523. //取得父节点
  524. string[] father_nodes = new string[nodes.Count() - 1];
  525. //对父节点进行初始化
  526. for (int i = 0; i < nodes.Count() - 1; i++)
  527. {
  528. father_nodes[i] = (string)nodes[i].Clone();
  529. }
  530. string fast_xpath = string.Join("/", father_nodes);
  531. XmlNode fastnode = xmlDoc.SelectSingleNode("/XmlConfig/" + fast_xpath);
  532. if (node == null)
  533. return;
  534. if (fastnode == null)
  535. return;
  536. //使用父节点删除子节点
  537. fastnode.RemoveChild(node);
  538. //保存
  539. xmlDoc.Save(_xmlPath);
  540. }
  541. //递归根据 xpath 的方式进行创建节点
  542. static private XmlNode makeXPath(XmlDocument doc, XmlNode parent, string xpath)
  543. {
  544. // 在XPath抓住下一个节点的名称;父级如果是空的则返回
  545. string[] partsOfXPath = xpath.Trim('/').Split('/');
  546. string nextNodeInXPath = partsOfXPath.First();
  547. if (string.IsNullOrEmpty(nextNodeInXPath))
  548. return parent;
  549. // 获取或从名称创建节点
  550. XmlNode node = parent.SelectSingleNode(nextNodeInXPath);
  551. if (node == null)
  552. node = parent.AppendChild(doc.CreateElement(nextNodeInXPath));
  553. // 加入的阵列作为一个XPath表达式和递归余数
  554. string rest = String.Join("/", partsOfXPath.Skip(1).ToArray());
  555. return makeXPath(doc, node, rest);
  556. }
  557. #endregion
  558. }
  559. }