XMLoperate.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  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. public static bool EditMemberXmlInfo(string FilePath, string TagName, string Name, string Value)
  295. {
  296. try
  297. {
  298. XmlDocument xmlDoc = new XmlDocument();
  299. xmlDoc.Load(FilePath); //加载Xml文件
  300. XmlNodeList nodeList = xmlDoc.GetElementsByTagName("Member");
  301. foreach (XmlNode node in nodeList)
  302. {
  303. XmlElement ele = (XmlElement)node;
  304. if (ele.GetAttribute("RegName") == TagName)
  305. {
  306. ele.SetAttribute(Name, Value);
  307. }
  308. }
  309. xmlDoc.Save(FilePath);
  310. return true;
  311. }
  312. catch /*(Exception e)*/
  313. {
  314. return false;
  315. }
  316. }
  317. /// <summary>
  318. /// 获取XML节点参数
  319. /// </summary>
  320. /// <param name="Name">节点参数名称</param>
  321. /// <returns>节点参数</returns>
  322. public static string GetXMLInformations(string xmlFilePath, string Name)
  323. {
  324. try
  325. {
  326. string value = string.Empty;
  327. XmlDocument doc = new XmlDocument();
  328. doc.Load(xmlFilePath); //加载Xml文件
  329. XmlElement root = doc.DocumentElement; //获取根节点
  330. XmlNodeList mainNodes = root.GetElementsByTagName("parameter"); //获取子节点集合
  331. foreach (XmlNode node in mainNodes)
  332. {
  333. //获取Name属性值
  334. string name = ((XmlElement)node).GetAttribute("Name");
  335. if (name.Equals(Name))
  336. {
  337. value = ((XmlElement)node).GetAttribute("Value");
  338. }
  339. }
  340. return value;
  341. }
  342. catch (Exception)
  343. {
  344. return "";
  345. }
  346. }
  347. /// <summary>
  348. /// 修改第二层节点数据
  349. /// </summary>
  350. /// <param name="XmlPath">XML路径</param>
  351. /// <param name="AttributeName">所有需要修改的属性名称</param>
  352. /// <param name="Value">需要修改的值</param>
  353. /// <returns></returns>
  354. public static bool UpdateByAttribute(string XmlPath, string[] AttributeName, string[] Value)
  355. {
  356. try
  357. {
  358. XmlDocument docXml = new XmlDocument();
  359. docXml.Load(@XmlPath);
  360. XmlNodeList xn = docXml.DocumentElement.ChildNodes;
  361. //遍历第一层节点
  362. foreach (XmlElement element in xn)
  363. {
  364. if (element.Attributes[0].Value == Value[0])
  365. {
  366. for (int i = 0; i < element.Attributes.Count; i++)
  367. {
  368. for (int j = 0; j < AttributeName.Count(); j++)
  369. {
  370. //判断父节点的属性值是否等于指定属性
  371. if (element.Attributes[i].Name == AttributeName[j])
  372. {
  373. element.SetAttribute(AttributeName[j], Value[j]);
  374. break;
  375. }
  376. }
  377. }
  378. break;
  379. }
  380. }
  381. docXml.Save(@XmlPath);
  382. return true;
  383. }
  384. catch /*(Exception e)*/
  385. {
  386. return false;
  387. }
  388. }
  389. public static int InsertAttribute(string XmlPath, string[] AttributeName, string[] Value, string nodeName)
  390. {
  391. try
  392. {
  393. XmlDocument docXml = new XmlDocument();
  394. docXml.Load(@XmlPath);
  395. XmlNodeList xn = docXml.DocumentElement.ChildNodes;
  396. foreach (XmlElement element in xn)
  397. {
  398. if (element.Attributes[0].Value == Value[0])
  399. {
  400. return -1;
  401. }
  402. }
  403. XmlElement xe = docXml.CreateElement(nodeName);
  404. for (int i = 0; i < AttributeName.Count(); i++)
  405. {
  406. xe.SetAttribute(AttributeName[i], Value[i]);
  407. }
  408. docXml.DocumentElement.AppendChild(xe);
  409. docXml.Save(@XmlPath);
  410. return 1;
  411. }
  412. catch /*(Exception e)*/
  413. {
  414. return 0;
  415. }
  416. }
  417. public static int DeleteByAttribute(string XmlPath, string AttributeName, string Value)
  418. {
  419. try
  420. {
  421. XmlDocument docXml = new XmlDocument();
  422. docXml.Load(@XmlPath);
  423. XmlNodeList xn = docXml.DocumentElement.ChildNodes;
  424. foreach (XmlElement element in xn)
  425. {
  426. if (element.Attributes[AttributeName].Value == Value)
  427. {
  428. element.ParentNode.RemoveChild(element);
  429. docXml.Save(@XmlPath);
  430. return 1;
  431. }
  432. }
  433. return 2;
  434. }
  435. catch /*(Exception e)*/
  436. {
  437. return 0;
  438. }
  439. }
  440. #region 报告模板
  441. /// <summary>
  442. /// 写入配置,也可以用来修改
  443. /// </summary>
  444. /// <param name="value">写入的值</param>
  445. /// <param name="nodes">节点</param>
  446. public void Write(string value, params string[] nodes)
  447. {
  448. //初始化xml
  449. XmlDocument xmlDoc = new XmlDocument();
  450. if (File.Exists(_xmlPath))
  451. xmlDoc.Load(_xmlPath);
  452. else
  453. xmlDoc.LoadXml("<XmlConfig />");
  454. XmlNode xmlRoot = xmlDoc.ChildNodes[0];
  455. //新增、编辑 节点
  456. string xpath = string.Join("/", nodes);
  457. XmlNode node = xmlDoc.SelectSingleNode(xpath);
  458. if (node == null) //新增节点
  459. {
  460. node = makeXPath(xmlDoc, xmlRoot, xpath);
  461. }
  462. node.InnerText = value;
  463. //保存
  464. xmlDoc.Save(_xmlPath);
  465. }
  466. /// <summary>
  467. /// 设置节点上属性的值
  468. /// </summary>
  469. /// <param name="AttributeName">属性名</param>
  470. /// <param name="AttributeValue">属性值</param>
  471. /// <param name="nodes">选择节点</param>
  472. public void SetAttribute(string AttributeName, string AttributeValue, params string[] nodes)
  473. {
  474. //初始化xml
  475. XmlDocument xmlDoc = new XmlDocument();
  476. if (File.Exists(_xmlPath))
  477. xmlDoc.Load(_xmlPath);
  478. else
  479. xmlDoc.LoadXml("<XmlConfig />");
  480. XmlNode xmlRoot = xmlDoc.ChildNodes[0];
  481. //新增、编辑 节点
  482. string xpath = string.Join("/", nodes);
  483. XmlElement element = (XmlElement)xmlDoc.SelectSingleNode(xpath);
  484. if (element == null) //新增节点
  485. {
  486. element = (XmlElement)makeXPath(xmlDoc, xmlRoot, xpath);
  487. }
  488. //设置节点上属性的值
  489. element.SetAttribute(AttributeName, AttributeValue);
  490. //保存
  491. xmlDoc.Save(_xmlPath);
  492. }
  493. public string GetAttribute(string AttributeName, params string[] nodes)
  494. {
  495. //初始化xml
  496. XmlDocument xmlDoc = new XmlDocument();
  497. if (File.Exists(_xmlPath))
  498. xmlDoc.Load(_xmlPath);
  499. else
  500. xmlDoc.LoadXml("<XmlConfig />");
  501. XmlNode xmlRoot = xmlDoc.ChildNodes[0];
  502. //新增、编辑 节点
  503. string xpath = string.Join("/", nodes);
  504. XmlElement element = (XmlElement)xmlDoc.SelectSingleNode(xpath);
  505. if (element == null) //新增节点
  506. {
  507. element = (XmlElement)makeXPath(xmlDoc, xmlRoot, xpath);
  508. }
  509. //设置节点上属性的值
  510. string retstr = element.GetAttribute(AttributeName);
  511. //保存
  512. xmlDoc.Save(_xmlPath);
  513. return retstr;
  514. }
  515. /// <summary>
  516. /// 读取配置
  517. /// </summary>
  518. /// <param name="nodes">节点</param>
  519. /// <returns></returns>
  520. public string Read(params string[] nodes)
  521. {
  522. XmlDocument xmlDoc = new XmlDocument();
  523. if (File.Exists(_xmlPath) == false)
  524. return null;
  525. else
  526. xmlDoc.Load(_xmlPath);
  527. string xpath = string.Join("/", nodes);
  528. XmlNode node = xmlDoc.SelectSingleNode("/XmlConfig/" + xpath);
  529. if (node == null)
  530. return null;
  531. return node.InnerText;
  532. }
  533. /// <summary>
  534. /// 删除节点
  535. /// </summary>
  536. /// <param name="nodes"></param>
  537. public void RemoveNode(params string[] nodes)
  538. {
  539. XmlDocument xmlDoc = new XmlDocument();
  540. if (File.Exists(_xmlPath) == false)
  541. return;
  542. else
  543. xmlDoc.Load(_xmlPath);
  544. string xpath = string.Join("/", nodes);
  545. XmlNode node = xmlDoc.SelectSingleNode("/XmlConfig/" + xpath);
  546. //取得父节点
  547. string[] father_nodes = new string[nodes.Count() - 1];
  548. //对父节点进行初始化
  549. for (int i = 0; i < nodes.Count() - 1; i++)
  550. {
  551. father_nodes[i] = (string)nodes[i].Clone();
  552. }
  553. string fast_xpath = string.Join("/", father_nodes);
  554. XmlNode fastnode = xmlDoc.SelectSingleNode("/XmlConfig/" + fast_xpath);
  555. if (node == null)
  556. return;
  557. if (fastnode == null)
  558. return;
  559. //使用父节点删除子节点
  560. fastnode.RemoveChild(node);
  561. //保存
  562. xmlDoc.Save(_xmlPath);
  563. }
  564. //递归根据 xpath 的方式进行创建节点
  565. static private XmlNode makeXPath(XmlDocument doc, XmlNode parent, string xpath)
  566. {
  567. // 在XPath抓住下一个节点的名称;父级如果是空的则返回
  568. string[] partsOfXPath = xpath.Trim('/').Split('/');
  569. string nextNodeInXPath = partsOfXPath.First();
  570. if (string.IsNullOrEmpty(nextNodeInXPath))
  571. return parent;
  572. // 获取或从名称创建节点
  573. XmlNode node = parent.SelectSingleNode(nextNodeInXPath);
  574. if (node == null)
  575. node = parent.AppendChild(doc.CreateElement(nextNodeInXPath));
  576. // 加入的阵列作为一个XPath表达式和递归余数
  577. string rest = String.Join("/", partsOfXPath.Skip(1).ToArray());
  578. return makeXPath(doc, node, rest);
  579. }
  580. #endregion
  581. }
  582. }