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