using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Xml;
namespace OTSCommon
{
public class XMLoperate
{
#region 读取XML到DataSet
///
/// 功能:读取XML到DataSet中
///
/// xml路径
/// DataSet
public static DataSet GetXml(string XmlPath)
{
DataSet ds = new DataSet();
ds.ReadXml(@XmlPath);
return ds;
}
#endregion
#region 读取xml文档并返回一个节点
///
/// 读取xml文档并返回一个节点:适用于一级节点
///
/// xml路径
/// 节点
///
public static string ReadXmlReturnNode(string XmlPath, string Node)
{
XmlDocument docXml = new XmlDocument();
docXml.Load(@XmlPath);
XmlNodeList xn = docXml.GetElementsByTagName(Node);
return xn.Item(0).InnerText.ToString();
}
#endregion
#region 查找数据,返回一个DataSet
///
/// 查找数据,返回当前节点的所有下级节点,填充到一个DataSet中
///
/// xml文档路径
/// 节点的路径:根节点/父节点/当前节点
///
public static DataSet GetXmlData(string xmlPath, string XmlPathNode)
{
XmlDocument objXmlDoc = new XmlDocument();
objXmlDoc.Load(xmlPath);
DataSet ds = new DataSet();
StringReader read = new StringReader(objXmlDoc.SelectSingleNode(XmlPathNode).OuterXml);
ds.ReadXml(read);
return ds;
}
#endregion
//必须创建对象才能使用的类
private bool _alreadyDispose = false;
private XmlDocument xmlDoc = new XmlDocument();
private string _xmlPath;
#region 构造与释构
public XMLoperate()
{
}
public XMLoperate(string xmlPath)
{
_xmlPath = xmlPath;
}
~XMLoperate()
{
Dispose();
}
protected virtual void Dispose(bool isDisposing)
{
if (_alreadyDispose) return;
if (isDisposing)
{
//
}
_alreadyDispose = true;
}
#endregion
#region IDisposable 成员
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
#region 根据父节点属性值读取子节点值
///
/// 根据父节点属性读取字节点值
///
/// xml路径
/// 父节点名
/// 属性值
/// 属性索引
/// 要返回的节点数组长度
///
public static System.Collections.ArrayList GetSubElementByAttribute(string XmlPath, string FatherElenetName, string AttributeName, int AttributeIndex, int ArrayLength)
{
System.Collections.ArrayList al = new System.Collections.ArrayList();
XmlDocument docXml = new XmlDocument();
docXml.Load(@XmlPath);
XmlNodeList xn = docXml.DocumentElement.ChildNodes;
//遍历第一层节点
foreach (XmlElement element in xn)
{
//判断父节点是否为指定节点
if (element.Name == FatherElenetName)
{
//判断父节点属性的索引是否大于指定索引
if (element.Attributes.Count < AttributeIndex)
return null;
//判断父节点的属性值是否等于指定属性
if (element.Attributes[AttributeIndex].Value == AttributeName)
{
XmlNodeList xx = element.ChildNodes;
if (xx.Count > 0)
{
for (int i = 0; i < ArrayLength & i < xx.Count; i++)
{
al.Add(xx[i].InnerText);
}
}
}
}
}
return al;
}
#endregion
#region 根据节点属性读取子节点值(较省资源模式)
///
/// 根据节点属性读取子节点值(较省资源模式)
///
/// xml路径
/// 父节点值
/// 属性名称
/// 属性值
/// 返回的数组长度
///
public static System.Collections.ArrayList GetSubElementByAttribute(string XmlPath, string FatherElement, string AttributeName, string AttributeValue, int ArrayLength)
{
System.Collections.ArrayList al = new System.Collections.ArrayList();
XmlDocument docXml = new XmlDocument();
docXml.Load(@XmlPath);
XmlNodeList xn;
xn = docXml.DocumentElement.SelectNodes("//" + FatherElement + "[" + @AttributeName + "='" + AttributeValue + "']");
XmlNodeList xx = xn.Item(0).ChildNodes;
for (int i = 0; i < ArrayLength & i < xx.Count; i++)
{
al.Add(xx.Item(i).InnerText);
}
return al;
}
#endregion
#region 根据父节点属性值读取子节点值
///
/// 根据父节点属性读取字节点值
///
/// xml路径
///
public static Dictionary GetXMLAllInfo(string XmlPath)
{
if (XmlPath == "")
{
return null;
}
Dictionary suggestions = new Dictionary();
XmlDocument docXml = new XmlDocument();
docXml.Load(@XmlPath);
XmlNodeList xn = docXml.DocumentElement.ChildNodes;
//遍历第一层节点
foreach (XmlElement element in xn)
{
string name = element.Name;
if ("Collection"!= name)
{
int attributes = element.Attributes.Count;
Dictionary obj = new Dictionary();
string key = "";
foreach (System.Xml.XmlAttribute item in element.Attributes)
{
if (item.Name == "RegName")
{
key = item.Value;
}
else
{
obj.Add(item.Name, item.Value);
}
}
if (element.ChildNodes.Count > 0)
{
Dictionary childList = GetChildInfo(element.ChildNodes);
if (childList.Count > 0)
{
obj.Add("Members", childList);
}
}
suggestions.Add(key, obj);
}
}
return suggestions;
}
private static Dictionary GetChildInfo(XmlNodeList childs)
{
Dictionary child = new Dictionary();
foreach (XmlElement element in childs)
{
if (element.Name != "Member")
continue;
int attributes = element.Attributes.Count;
Dictionary obj = new Dictionary();
string key = "";
foreach (System.Xml.XmlAttribute item in element.Attributes)
{
if (item.Name == "RegName")
{
key = item.Value;
}
else
{
obj.Add(item.Name, item.Value);
}
}
if (element.ChildNodes.Count > 0)
{
Dictionary childList = GetChildInfo(element.ChildNodes);
if (childList.Count > 0)
{
obj.Add("Members", childList);
}
}
child.Add(key, obj);
}
return child;
}
#endregion
public static List GetMember(string XmlPath, string tem)
{
if (XmlPath == "")
{
return null;
}
XmlDocument docXml = new XmlDocument();
docXml.Load(@XmlPath);
XmlNodeList xn = docXml.DocumentElement.ChildNodes[0].ChildNodes;
List elem = new List();
//遍历第一层节点
foreach (XmlElement element in xn)
{
foreach (System.Xml.XmlAttribute item in element.Attributes)
{
if (item.Name == "TemplateName" && item.Value == tem)
{
elem.Add(element.ChildNodes[0].ChildNodes[0].Attributes["ElementName"].Value);
elem.Add(element.ChildNodes[0].ChildNodes[1].Attributes["ElementName"].Value);
elem.Add(element.ChildNodes[0].ChildNodes[2].Attributes["ElementName"].Value);
return elem;
}
}
}
return elem;
}
///
/// 修改xml
///
/// 文件地址
/// 节点名称
/// 节点属性名称
/// 节点属性值
public static bool EditXmlInfo(string FilePath, string TagName, string Name, string Value)
{
try
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(FilePath); //加载Xml文件
XmlNodeList nodeList = xmlDoc.GetElementsByTagName(TagName);
foreach (XmlNode node in nodeList)
{
XmlElement ele = (XmlElement)node;
ele.SetAttribute(Name, Value);
}
xmlDoc.Save(FilePath);
return true;
}
catch /*(Exception e)*/
{
return false;
}
}
public static bool EditMemberXmlInfo(string FilePath, string TagName, string Name, string Value)
{
try
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(FilePath); //加载Xml文件
XmlNodeList nodeList = xmlDoc.GetElementsByTagName("Member");
foreach (XmlNode node in nodeList)
{
XmlElement ele = (XmlElement)node;
if (ele.GetAttribute("RegName") == TagName)
{
ele.SetAttribute(Name, Value);
}
}
xmlDoc.Save(FilePath);
return true;
}
catch /*(Exception e)*/
{
return false;
}
}
///
/// 获取XML节点参数
///
/// 节点参数名称
/// 节点参数
public static string GetXMLInformations(string xmlFilePath, string Name)
{
try
{
string value = string.Empty;
XmlDocument doc = new XmlDocument();
doc.Load(xmlFilePath); //加载Xml文件
XmlElement root = doc.DocumentElement; //获取根节点
XmlNodeList mainNodes = root.GetElementsByTagName("parameter"); //获取子节点集合
foreach (XmlNode node in mainNodes)
{
//获取Name属性值
string name = ((XmlElement)node).GetAttribute("Name");
if (name.Equals(Name))
{
value = ((XmlElement)node).GetAttribute("Value");
}
}
return value;
}
catch (Exception)
{
return "";
}
}
///
/// 修改第二层节点数据
///
/// XML路径
/// 所有需要修改的属性名称
/// 需要修改的值
///
public static bool UpdateByAttribute(string XmlPath, string[] AttributeName, string[] Value)
{
try
{
XmlDocument docXml = new XmlDocument();
docXml.Load(@XmlPath);
XmlNodeList xn = docXml.DocumentElement.ChildNodes;
//遍历第一层节点
foreach (XmlElement element in xn)
{
if (element.Attributes[0].Value == Value[0])
{
for (int i = 0; i < element.Attributes.Count; i++)
{
for (int j = 0; j < AttributeName.Count(); j++)
{
//判断父节点的属性值是否等于指定属性
if (element.Attributes[i].Name == AttributeName[j])
{
element.SetAttribute(AttributeName[j], Value[j]);
break;
}
}
}
break;
}
}
docXml.Save(@XmlPath);
return true;
}
catch /*(Exception e)*/
{
return false;
}
}
public static int InsertAttribute(string XmlPath, string[] AttributeName, string[] Value, string nodeName)
{
try
{
XmlDocument docXml = new XmlDocument();
docXml.Load(@XmlPath);
XmlNodeList xn = docXml.DocumentElement.ChildNodes;
foreach (XmlElement element in xn)
{
if (element.Attributes[0].Value == Value[0])
{
return -1;
}
}
XmlElement xe = docXml.CreateElement(nodeName);
for (int i = 0; i < AttributeName.Count(); i++)
{
xe.SetAttribute(AttributeName[i], Value[i]);
}
docXml.DocumentElement.AppendChild(xe);
docXml.Save(@XmlPath);
return 1;
}
catch /*(Exception e)*/
{
return 0;
}
}
public static int DeleteByAttribute(string XmlPath, string AttributeName, string Value)
{
try
{
XmlDocument docXml = new XmlDocument();
docXml.Load(@XmlPath);
XmlNodeList xn = docXml.DocumentElement.ChildNodes;
foreach (XmlElement element in xn)
{
if (element.Attributes[AttributeName].Value == Value)
{
element.ParentNode.RemoveChild(element);
docXml.Save(@XmlPath);
return 1;
}
}
return 2;
}
catch /*(Exception e)*/
{
return 0;
}
}
#region 报告模板
///
/// 写入配置,也可以用来修改
///
/// 写入的值
/// 节点
public void Write(string value, params string[] nodes)
{
//初始化xml
XmlDocument xmlDoc = new XmlDocument();
if (File.Exists(_xmlPath))
xmlDoc.Load(_xmlPath);
else
xmlDoc.LoadXml("");
XmlNode xmlRoot = xmlDoc.ChildNodes[0];
//新增、编辑 节点
string xpath = string.Join("/", nodes);
XmlNode node = xmlDoc.SelectSingleNode(xpath);
if (node == null) //新增节点
{
node = makeXPath(xmlDoc, xmlRoot, xpath);
}
node.InnerText = value;
//保存
xmlDoc.Save(_xmlPath);
}
///
/// 设置节点上属性的值
///
/// 属性名
/// 属性值
/// 选择节点
public void SetAttribute(string AttributeName, string AttributeValue, params string[] nodes)
{
//初始化xml
XmlDocument xmlDoc = new XmlDocument();
if (File.Exists(_xmlPath))
xmlDoc.Load(_xmlPath);
else
xmlDoc.LoadXml("");
XmlNode xmlRoot = xmlDoc.ChildNodes[0];
//新增、编辑 节点
string xpath = string.Join("/", nodes);
XmlElement element = (XmlElement)xmlDoc.SelectSingleNode(xpath);
if (element == null) //新增节点
{
element = (XmlElement)makeXPath(xmlDoc, xmlRoot, xpath);
}
//设置节点上属性的值
element.SetAttribute(AttributeName, AttributeValue);
//保存
xmlDoc.Save(_xmlPath);
}
public string GetAttribute(string AttributeName, params string[] nodes)
{
//初始化xml
XmlDocument xmlDoc = new XmlDocument();
if (File.Exists(_xmlPath))
xmlDoc.Load(_xmlPath);
else
xmlDoc.LoadXml("");
XmlNode xmlRoot = xmlDoc.ChildNodes[0];
//新增、编辑 节点
string xpath = string.Join("/", nodes);
XmlElement element = (XmlElement)xmlDoc.SelectSingleNode(xpath);
if (element == null) //新增节点
{
element = (XmlElement)makeXPath(xmlDoc, xmlRoot, xpath);
}
//设置节点上属性的值
string retstr = element.GetAttribute(AttributeName);
//保存
xmlDoc.Save(_xmlPath);
return retstr;
}
///
/// 读取配置
///
/// 节点
///
public string Read(params string[] nodes)
{
XmlDocument xmlDoc = new XmlDocument();
if (File.Exists(_xmlPath) == false)
return null;
else
xmlDoc.Load(_xmlPath);
string xpath = string.Join("/", nodes);
XmlNode node = xmlDoc.SelectSingleNode("/XmlConfig/" + xpath);
if (node == null)
return null;
return node.InnerText;
}
///
/// 删除节点
///
///
public void RemoveNode(params string[] nodes)
{
XmlDocument xmlDoc = new XmlDocument();
if (File.Exists(_xmlPath) == false)
return;
else
xmlDoc.Load(_xmlPath);
string xpath = string.Join("/", nodes);
XmlNode node = xmlDoc.SelectSingleNode("/XmlConfig/" + xpath);
//取得父节点
string[] father_nodes = new string[nodes.Count() - 1];
//对父节点进行初始化
for (int i = 0; i < nodes.Count() - 1; i++)
{
father_nodes[i] = (string)nodes[i].Clone();
}
string fast_xpath = string.Join("/", father_nodes);
XmlNode fastnode = xmlDoc.SelectSingleNode("/XmlConfig/" + fast_xpath);
if (node == null)
return;
if (fastnode == null)
return;
//使用父节点删除子节点
fastnode.RemoveChild(node);
//保存
xmlDoc.Save(_xmlPath);
}
//递归根据 xpath 的方式进行创建节点
static private XmlNode makeXPath(XmlDocument doc, XmlNode parent, string xpath)
{
// 在XPath抓住下一个节点的名称;父级如果是空的则返回
string[] partsOfXPath = xpath.Trim('/').Split('/');
string nextNodeInXPath = partsOfXPath.First();
if (string.IsNullOrEmpty(nextNodeInXPath))
return parent;
// 获取或从名称创建节点
XmlNode node = parent.SelectSingleNode(nextNodeInXPath);
if (node == null)
node = parent.AppendChild(doc.CreateElement(nextNodeInXPath));
// 加入的阵列作为一个XPath表达式和递归余数
string rest = String.Join("/", partsOfXPath.Skip(1).ToArray());
return makeXPath(doc, node, rest);
}
#endregion
#region 特殊颗粒XML处理
///
/// 特殊颗粒XML读取
///
/// 文件地址
/// 节点名称
/// DataSet
public static DataSet GetXMLRegList(string FilePath, string TagName)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(FilePath); //加载Xml文件
XmlNodeList nodeList = xmlDoc.GetElementsByTagName(TagName);
List dsList = new List();
DataSet dsResult = new DataSet();
foreach (XmlNode node in nodeList)
{
XmlElement ele = (XmlElement)node;
DataSet dsn = new DataSet();
StringReader read = new StringReader(node.OuterXml);
dsn.ReadXml(read);
dsList.Add(dsn);
}
for (int i = 0; i < dsList.Count; i++)
{
if (i == 0)
{
dsResult = dsList[i];
}
else
{
dsResult.Merge(dsList[i], false, MissingSchemaAction.Ignore);
}
}
return dsResult;
}
public static bool UpdateSpecialGrayXMLFile(string FilePath, DataGridView dg,bool isToRun)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(FilePath); //加载Xml文件
xmlDoc.RemoveAll();
XmlElement xmlData = xmlDoc.CreateElement("XMLData");
xmlDoc.AppendChild(xmlData);
if (isToRun)
{
xmlData.SetAttribute("ToRun", "True");
}
else
{
xmlData.SetAttribute("ToRun", "False");
}
XmlElement membercol = xmlDoc.CreateElement("Collection");
membercol.SetAttribute("RegName", "GrayRangeList");
xmlData.AppendChild(membercol);
for (int i = 0; i < dg.Rows.Count; i++)
{
XmlElement member = xmlDoc.CreateElement("Member");
membercol.AppendChild(member);
for (int j = 0; j < dg.Columns.Count; j++)
{
//设置参数
member.SetAttribute("RegName", dg.Rows[i].Cells["RegName"].Value.ToString());
member.SetAttribute("start", dg.Rows[i].Cells["start"].Value.ToString());
member.SetAttribute("end", dg.Rows[i].Cells["end"].Value.ToString());
member.SetAttribute("diameterStart", dg.Rows[i].Cells["diameterStart"].Value.ToString());
member.SetAttribute("diameterEnd", dg.Rows[i].Cells["diameterEnd"].Value.ToString());
if (dg.Rows[i].Cells["collectXray"].Value==DBNull.Value || dg.Rows[i].Cells["collectXray"].Value.ToString() == "false")
{
member.SetAttribute("collectXray", "false");
}
else
{
member.SetAttribute("collectXray", "true");
}
}
}
xmlDoc.Save(FilePath);
return true;
}
#endregion
}
}