XMLoperate.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  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. int attributes = element.Attributes.Count;
  179. Dictionary<string, object> obj = new Dictionary<string, object>();
  180. string key = "";
  181. foreach (System.Xml.XmlAttribute item in element.Attributes)
  182. {
  183. if (item.Name == "RegName")
  184. {
  185. key = item.Value;
  186. }
  187. else
  188. {
  189. obj.Add(item.Name, item.Value);
  190. }
  191. }
  192. if (element.ChildNodes.Count > 0)
  193. {
  194. Dictionary<string, object> childList = GetChildInfo(element.ChildNodes);
  195. if (childList.Count > 0)
  196. {
  197. obj.Add("Members", childList);
  198. }
  199. }
  200. suggestions.Add(key, obj);
  201. }
  202. return suggestions;
  203. }
  204. private static Dictionary<string, object> GetChildInfo(XmlNodeList childs)
  205. {
  206. Dictionary<string, object> child = new Dictionary<string, object>();
  207. foreach (XmlElement element in childs)
  208. {
  209. if (element.Name != "Member")
  210. continue;
  211. int attributes = element.Attributes.Count;
  212. Dictionary<string, object> obj = new Dictionary<string, object>();
  213. string key = "";
  214. foreach (System.Xml.XmlAttribute item in element.Attributes)
  215. {
  216. if (item.Name == "RegName")
  217. {
  218. key = item.Value;
  219. }
  220. else
  221. {
  222. obj.Add(item.Name, item.Value);
  223. }
  224. }
  225. if (element.ChildNodes.Count > 0)
  226. {
  227. Dictionary<string, object> childList = GetChildInfo(element.ChildNodes);
  228. if (childList.Count > 0)
  229. {
  230. obj.Add("Members", childList);
  231. }
  232. }
  233. child.Add(key, obj);
  234. }
  235. return child;
  236. }
  237. #endregion
  238. public static List<string> GetMember(string XmlPath, string tem)
  239. {
  240. if (XmlPath == "")
  241. {
  242. return null;
  243. }
  244. XmlDocument docXml = new XmlDocument();
  245. docXml.Load(@XmlPath);
  246. XmlNodeList xn = docXml.DocumentElement.ChildNodes[0].ChildNodes;
  247. List<string> elem = new List<string>();
  248. //遍历第一层节点
  249. foreach (XmlElement element in xn)
  250. {
  251. foreach (System.Xml.XmlAttribute item in element.Attributes)
  252. {
  253. if (item.Name == "TemplateName" && item.Value == tem)
  254. {
  255. elem.Add(element.ChildNodes[0].ChildNodes[0].Attributes["ElementName"].Value);
  256. elem.Add(element.ChildNodes[0].ChildNodes[1].Attributes["ElementName"].Value);
  257. elem.Add(element.ChildNodes[0].ChildNodes[2].Attributes["ElementName"].Value);
  258. return elem;
  259. }
  260. }
  261. }
  262. return elem;
  263. }
  264. /// <summary>
  265. /// 修改xml
  266. /// </summary>
  267. /// <param name="FilePath">文件地址</param>
  268. /// <param name="RegName">节点名称</param>
  269. /// <param name="Name">节点属性名称</param>
  270. /// <param name="Value">节点属性值</param>
  271. public static bool EditXmlInfo(string FilePath, string TagName, string Name, string Value)
  272. {
  273. try
  274. {
  275. XmlDocument xmlDoc = new XmlDocument();
  276. xmlDoc.Load(FilePath); //加载Xml文件
  277. XmlNodeList nodeList = xmlDoc.GetElementsByTagName(TagName);
  278. foreach (XmlNode node in nodeList)
  279. {
  280. XmlElement ele = (XmlElement)node;
  281. ele.SetAttribute(Name, Value);
  282. }
  283. xmlDoc.Save(FilePath);
  284. return true;
  285. }
  286. catch (Exception e)
  287. {
  288. return false;
  289. }
  290. }
  291. /// <summary>
  292. /// 获取XML节点参数
  293. /// </summary>
  294. /// <param name="Name">节点参数名称</param>
  295. /// <returns>节点参数</returns>
  296. public static string GetXMLInformations(string xmlFilePath, string Name)
  297. {
  298. try
  299. {
  300. string value = string.Empty;
  301. XmlDocument doc = new XmlDocument();
  302. doc.Load(xmlFilePath); //加载Xml文件
  303. XmlElement root = doc.DocumentElement; //获取根节点
  304. XmlNodeList mainNodes = root.GetElementsByTagName("parameter"); //获取子节点集合
  305. foreach (XmlNode node in mainNodes)
  306. {
  307. //获取Name属性值
  308. string name = ((XmlElement)node).GetAttribute("Name");
  309. if (name.Equals(Name))
  310. {
  311. value = ((XmlElement)node).GetAttribute("Value");
  312. }
  313. }
  314. return value;
  315. }
  316. catch (Exception)
  317. {
  318. return "";
  319. }
  320. }
  321. /// <summary>
  322. /// 修改第二层节点数据
  323. /// </summary>
  324. /// <param name="XmlPath">XML路径</param>
  325. /// <param name="AttributeName">所有需要修改的属性名称</param>
  326. /// <param name="Value">需要修改的值</param>
  327. /// <returns></returns>
  328. public static bool UpdateByAttribute(string XmlPath, string[] AttributeName, string[] Value)
  329. {
  330. try
  331. {
  332. XmlDocument docXml = new XmlDocument();
  333. docXml.Load(@XmlPath);
  334. XmlNodeList xn = docXml.DocumentElement.ChildNodes;
  335. //遍历第一层节点
  336. foreach (XmlElement element in xn)
  337. {
  338. if (element.Attributes[0].Value == Value[0])
  339. {
  340. for (int i = 0; i < element.Attributes.Count; i++)
  341. {
  342. for (int j = 0; j < AttributeName.Count(); j++)
  343. {
  344. //判断父节点的属性值是否等于指定属性
  345. if (element.Attributes[i].Name == AttributeName[j])
  346. {
  347. element.SetAttribute(AttributeName[j], Value[j]);
  348. break;
  349. }
  350. }
  351. }
  352. break;
  353. }
  354. }
  355. docXml.Save(@XmlPath);
  356. return true;
  357. }
  358. catch (Exception e)
  359. {
  360. return false;
  361. }
  362. }
  363. public static int InsertAttribute(string XmlPath, string[] AttributeName, string[] Value, string nodeName)
  364. {
  365. try
  366. {
  367. XmlDocument docXml = new XmlDocument();
  368. docXml.Load(@XmlPath);
  369. XmlNodeList xn = docXml.DocumentElement.ChildNodes;
  370. foreach (XmlElement element in xn)
  371. {
  372. if (element.Attributes[0].Value == Value[0])
  373. {
  374. return -1;
  375. }
  376. }
  377. XmlElement xe = docXml.CreateElement(nodeName);
  378. for (int i = 0; i < AttributeName.Count(); i++)
  379. {
  380. xe.SetAttribute(AttributeName[i], Value[i]);
  381. }
  382. docXml.DocumentElement.AppendChild(xe);
  383. docXml.Save(@XmlPath);
  384. return 1;
  385. }
  386. catch (Exception e)
  387. {
  388. return 0;
  389. }
  390. }
  391. public static int DeleteByAttribute(string XmlPath, string AttributeName, string Value)
  392. {
  393. try
  394. {
  395. XmlDocument docXml = new XmlDocument();
  396. docXml.Load(@XmlPath);
  397. XmlNodeList xn = docXml.DocumentElement.ChildNodes;
  398. foreach (XmlElement element in xn)
  399. {
  400. if (element.Attributes[AttributeName].Value == Value)
  401. {
  402. element.ParentNode.RemoveChild(element);
  403. docXml.Save(@XmlPath);
  404. return 1;
  405. }
  406. }
  407. return 2;
  408. }
  409. catch (Exception e)
  410. {
  411. return 0;
  412. }
  413. }
  414. #region 报告模板
  415. /// <summary>
  416. /// 写入配置,也可以用来修改
  417. /// </summary>
  418. /// <param name="value">写入的值</param>
  419. /// <param name="nodes">节点</param>
  420. public void Write(string value, params string[] nodes)
  421. {
  422. //初始化xml
  423. XmlDocument xmlDoc = new XmlDocument();
  424. if (File.Exists(_xmlPath))
  425. xmlDoc.Load(_xmlPath);
  426. else
  427. xmlDoc.LoadXml("<XmlConfig />");
  428. XmlNode xmlRoot = xmlDoc.ChildNodes[0];
  429. //新增、编辑 节点
  430. string xpath = string.Join("/", nodes);
  431. XmlNode node = xmlDoc.SelectSingleNode(xpath);
  432. if (node == null) //新增节点
  433. {
  434. node = makeXPath(xmlDoc, xmlRoot, xpath);
  435. }
  436. node.InnerText = value;
  437. //保存
  438. xmlDoc.Save(_xmlPath);
  439. }
  440. /// <summary>
  441. /// 设置节点上属性的值
  442. /// </summary>
  443. /// <param name="AttributeName">属性名</param>
  444. /// <param name="AttributeValue">属性值</param>
  445. /// <param name="nodes">选择节点</param>
  446. public void SetAttribute(string AttributeName, string AttributeValue, 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. XmlElement element = (XmlElement)xmlDoc.SelectSingleNode(xpath);
  458. if (element == null) //新增节点
  459. {
  460. element = (XmlElement)makeXPath(xmlDoc, xmlRoot, xpath);
  461. }
  462. //设置节点上属性的值
  463. element.SetAttribute(AttributeName, AttributeValue);
  464. //保存
  465. xmlDoc.Save(_xmlPath);
  466. }
  467. public string GetAttribute(string AttributeName, params string[] nodes)
  468. {
  469. //初始化xml
  470. XmlDocument xmlDoc = new XmlDocument();
  471. if (File.Exists(_xmlPath))
  472. xmlDoc.Load(_xmlPath);
  473. else
  474. xmlDoc.LoadXml("<XmlConfig />");
  475. XmlNode xmlRoot = xmlDoc.ChildNodes[0];
  476. //新增、编辑 节点
  477. string xpath = string.Join("/", nodes);
  478. XmlElement element = (XmlElement)xmlDoc.SelectSingleNode(xpath);
  479. if (element == null) //新增节点
  480. {
  481. element = (XmlElement)makeXPath(xmlDoc, xmlRoot, xpath);
  482. }
  483. //设置节点上属性的值
  484. string retstr = element.GetAttribute(AttributeName);
  485. //保存
  486. xmlDoc.Save(_xmlPath);
  487. return retstr;
  488. }
  489. /// <summary>
  490. /// 读取配置
  491. /// </summary>
  492. /// <param name="nodes">节点</param>
  493. /// <returns></returns>
  494. public string Read(params string[] nodes)
  495. {
  496. XmlDocument xmlDoc = new XmlDocument();
  497. if (File.Exists(_xmlPath) == false)
  498. return null;
  499. else
  500. xmlDoc.Load(_xmlPath);
  501. string xpath = string.Join("/", nodes);
  502. XmlNode node = xmlDoc.SelectSingleNode("/XmlConfig/" + xpath);
  503. if (node == null)
  504. return null;
  505. return node.InnerText;
  506. }
  507. /// <summary>
  508. /// 删除节点
  509. /// </summary>
  510. /// <param name="nodes"></param>
  511. public void RemoveNode(params string[] nodes)
  512. {
  513. XmlDocument xmlDoc = new XmlDocument();
  514. if (File.Exists(_xmlPath) == false)
  515. return;
  516. else
  517. xmlDoc.Load(_xmlPath);
  518. string xpath = string.Join("/", nodes);
  519. XmlNode node = xmlDoc.SelectSingleNode("/XmlConfig/" + xpath);
  520. //取得父节点
  521. string[] father_nodes = new string[nodes.Count() - 1];
  522. //对父节点进行初始化
  523. for (int i = 0; i < nodes.Count() - 1; i++)
  524. {
  525. father_nodes[i] = (string)nodes[i].Clone();
  526. }
  527. string fast_xpath = string.Join("/", father_nodes);
  528. XmlNode fastnode = xmlDoc.SelectSingleNode("/XmlConfig/" + fast_xpath);
  529. if (node == null)
  530. return;
  531. if (fastnode == null)
  532. return;
  533. //使用父节点删除子节点
  534. fastnode.RemoveChild(node);
  535. //保存
  536. xmlDoc.Save(_xmlPath);
  537. }
  538. //递归根据 xpath 的方式进行创建节点
  539. static private XmlNode makeXPath(XmlDocument doc, XmlNode parent, string xpath)
  540. {
  541. // 在XPath抓住下一个节点的名称;父级如果是空的则返回
  542. string[] partsOfXPath = xpath.Trim('/').Split('/');
  543. string nextNodeInXPath = partsOfXPath.First();
  544. if (string.IsNullOrEmpty(nextNodeInXPath))
  545. return parent;
  546. // 获取或从名称创建节点
  547. XmlNode node = parent.SelectSingleNode(nextNodeInXPath);
  548. if (node == null)
  549. node = parent.AppendChild(doc.CreateElement(nextNodeInXPath));
  550. // 加入的阵列作为一个XPath表达式和递归余数
  551. string rest = String.Join("/", partsOfXPath.Skip(1).ToArray());
  552. return makeXPath(doc, node, rest);
  553. }
  554. #endregion
  555. }
  556. }