using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;
namespace WebApplication2
{
/// <summary>
/// XMLHelper XML文档操作管理器
/// </summary>
public class XMLHelper
{
public XMLHelper()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
#region XML文档节点查询和读取
/// <summary>
/// 选择匹配XPath表达式的第一个节点XmlNode.
/// </summary>
/// <param name="xmlFileName">XML文档完全文件名(包含物理路径)</param>
/// <param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名")</param>
/// <returns>返回XmlNode</returns>
public static XmlNode GetXmlNodeByXpath(string xmlFileName, string xpath)
{
XmlDocument xmlDoc = new XmlDocument();
try
{
xmlDoc.Load(xmlFileName); //加载XML文档
XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
return xmlNode;
}
catch (Exception ex)
{
return null;
//throw ex; //这里可以定义你自己的异常处理
}
}
/// <summary>
/// 选择匹配XPath表达式的节点列表XmlNodeList.
/// </summary>
/// <param name="xmlFileName">XML文档完全文件名(包含物理路径)</param>
/// <param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名")</param>
/// <returns>返回XmlNodeList</returns>
public static XmlNodeList GetXmlNodeListByXpath(string xmlFileName, string xpath)
{
XmlDocument xmlDoc = new XmlDocument();
try
{
xmlDoc.Load(xmlFileName); //加载XML文档
XmlNodeList xmlNodeList = xmlDoc.SelectNodes(xpath);
return xmlNodeList;
}
catch (Exception ex)
{
return null;
//throw ex; //这里可以定义你自己的异常处理
}
}
/// <summary>
/// 选择匹配XPath表达式的第一个节点的匹配xmlAttributeName的属性XmlAttribute.
/// </summary>
/// <param name="xmlFileName">XML文档完全文件名(包含物理路径)</param>
/// <param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名</param>
/// <param name="xmlAttributeName">要匹配xmlAttributeName的属性名称</param>
/// <returns>返回xmlAttributeName</returns>
public static XmlAttribute GetXmlAttribute(string xmlFileName, string xpath, string xmlAttributeName)
{
string content = string.Empty;
XmlDocument xmlDoc = new XmlDocument();
XmlAttribute xmlAttribute = null;
try
{
xmlDoc.Load(xmlFileName); //加载XML文档
XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
if (xmlNode != null)
{
if (xmlNode.Attributes.Count > 0)
{
xmlAttribute = xmlNode.Attributes[xmlAttributeName];
}
}
}
catch (Exception ex)
{
throw ex; //这里可以定义你自己的异常处理
}
return xmlAttribute;
}
#endregion
#region XML文档创建和节点或属性的添加、修改
/// <summary>
/// 创建一个XML文档
/// </summary>
/// <param name="xmlFileName">XML文档完全文件名(包含物理路径)</param>
/// <param name="rootNodeName">XML文档根节点名称(须指定一个根节点名称)</param>
/// <param name="version">XML文档版本号(必须为:"1.0")</param>
/// <param name="encoding">XML文档编码方式</param>
/// <param name="standalone">该值必须是"yes"或"no",如果为null,Save方法不在XML声明上写出独立属性</param>
/// <returns>成功返回true,失败返回false</returns>
public static bool CreateXmlDocument(string xmlFileName, string rootNodeName, string version, string encoding, string standalone)
{
bool isSuccess = false;
try
{
XmlDocument xmlDoc = new XmlDocument();
XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration(version, encoding, standalone);
XmlNode root = xmlDoc.CreateElement(rootNodeName);
xmlDoc.AppendChild(xmlDeclaration);
xmlDoc.AppendChild(root);
xmlDoc.Save(xmlFileName);
isSuccess = true;
}
catch (Exception ex)
{
throw ex; //这里可以定义你自己的异常处理
}
return isSuccess;
}
/// <summary>
/// 依据匹配XPath表达式的第一个节点来创建它的子节点(如果此节点已存在则追加一个新的同名节点
/// </summary>
/// <param name="xmlFileName">XML文档完全文件名(包含物理路径)</param>
/// <param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名</param>
/// <param name="xmlNodeName">要匹配xmlNodeName的节点名称</param>
/// <param name="innerText">节点文本值</param>
/// <param name="xmlAttributeName">要匹配xmlAttributeName的属性名称</param>
/// <param name="value">属性值</param>
/// <returns>成功返回true,失败返回false</returns>
public static bool CreateXmlNodeByXPath(string xmlFileName, string xpath, string xmlNodeName, string innerText, string xmlAttributeName, string value)
{
bool isSuccess = false;
XmlDocument xmlDoc = new XmlDocument();
try
{
xmlDoc.Load(xmlFileName); //加载XML文档
XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
if (xmlNode != null)
{
//存不存在此节点都创建
XmlElement subElement = xmlDoc.CreateElement(xmlNodeName);
subElement.InnerXml = innerText;
//如果属性和值参数都不为空则在此新节点上新增属性
if (!string.IsNullOrEmpty(xmlAttributeName) && !string.IsNullOrEmpty(value))
{
XmlAttribute xmlAttribute = xmlDoc.CreateAttribute(xmlAttributeName);
xmlAttribute.Value = value;
subElement.Attributes.Append(xmlAttribute);
}
xmlNode.AppendChild(subElement);
}
xmlDoc.Save(xmlFileName); //保存到XML文档
isSuccess = true;
}
catch (Exception ex)
{
throw ex; //这里可以定义你自己的异常处理
}
return isSuccess;
}
/// <summary>
/// 依据匹配XPath表达式的第一个节点来创建或更新它的子节点(如果节点存在则更新,不存在则创建)
/// </summary>
/// <param name="xmlFileName">XML文档完全文件名(包含物理路径)</param>
/// <param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名</param>
/// <param name="xmlNodeName">要匹配xmlNodeName的节点名称</param>
/// <param name="innerText">节点文本值</param>
/// <returns>成功返回true,失败返回false</returns>
public static bool CreateOrUpdateXmlNodeByXPath(string xmlFileName, string xpath, string xmlNodeName, string innerText)
{
bool isSuccess = false;
bool isExistsNode = false;//标识节点是否存在
XmlDocument xmlDoc = new XmlDocument();
try
{
xmlDoc.Load(xmlFileName); //加载XML文档
XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
if (xmlNode != null)
{
//遍历xpath节点下的所有子节点
foreach (XmlNode node in xmlNode.ChildNodes)
{
if (node.Name.ToLower() == xmlNodeName.ToLower())
{
//存在此节点则更新
node.InnerXml = innerText;
isExistsNode = true;
break;
}
}
if (!isExistsNode)
{
//不存在此节点则创建
XmlElement subElement = xmlDoc.CreateElement(xmlNodeName);
subElement.InnerXml = innerText;
xmlNode.AppendChild(subElement);
}
}
xmlDoc.Save(xmlFileName); //保存到XML文档
isSuccess = true;
}
catch (Exception ex)
{
throw ex; //这里可以定义你自己的异常处理
}
return isSuccess;
}
/// <summary>
/// 依据匹配XPath表达式的第一个节点来创建或更新它的属性(如果属性存在则更新,不存在则创建)
/// </summary>
/// <param name="xmlFileName">XML文档完全文件名(包含物理路径)</param>
/// <param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名</param>
/// <param name="xmlAttributeName">要匹配xmlAttributeName的属性名称</param>
/// <param name="value">属性值</param>
/// <returns>成功返回true,失败返回false</returns>
public static bool CreateOrUpdateXmlAttributeByXPath(string xmlFileName, string xpath, string xmlAttributeName, string value)
{
bool isSuccess = false;
bool isExistsAttribute = false;//标识属性是否存在
XmlDocument xmlDoc = new XmlDocument();
try
{
xmlDoc.Load(xmlFileName); //加载XML文档
XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
if (xmlNode != null)
{
//遍历xpath节点中的所有属性
foreach (XmlAttribute attribute in xmlNode.Attributes)
{
if (attribute.Name.ToLower() == xmlAttributeName.ToLower())
{
//节点中存在此属性则更新
attribute.Value = value;
isExistsAttribute = true;
break;
}
}
if (!isExistsAttribute)
{
//节点中不存在此属性则创建
XmlAttribute xmlAttribute = xmlDoc.CreateAttribute(xmlAttributeName);
xmlAttribute.Value = value;
xmlNode.Attributes.Append(xmlAttribute);
}
}
xmlDoc.Save(xmlFileName); //保存到XML文档
isSuccess = true;
}
catch (Exception ex)
{
throw ex; //这里可以定义你自己的异常处理
}
return isSuccess;
}
#endregion
#region XML文档节点或属性的删除
/// <summary>
/// 删除匹配XPath表达式的第一个节点(节点中的子元素同时会被删除)
/// </summary>
/// <param name="xmlFileName">XML文档完全文件名(包含物理路径)</param>
/// <param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名</param>
/// <returns>成功返回true,失败返回false</returns>
public static bool DeleteXmlNodeByXPath(string xmlFileName, string xpath)
{
bool isSuccess = false;
XmlDocument xmlDoc = new XmlDocument();
try
{
xmlDoc.Load(xmlFileName); //加载XML文档
XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
if (xmlNode != null)
{
//删除节点
xmlNode.ParentNode.RemoveChild(xmlNode);
}
xmlDoc.Save(xmlFileName); //保存到XML文档
isSuccess = true;
}
catch (Exception ex)
{
throw ex; //这里可以定义你自己的异常处理
}
return isSuccess;
}
/// <summary>
/// 删除匹配XPath表达式的第一个节点中的匹配参数xmlAttributeName的属性
/// </summary>
/// <param name="xmlFileName">XML文档完全文件名(包含物理路径)</param>
/// <param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名</param>
/// <param name="xmlAttributeName">要删除的xmlAttributeName的属性名称</param>
/// <returns>成功返回true,失败返回false</returns>
public static bool DeleteXmlAttributeByXPath(string xmlFileName, string xpath, string xmlAttributeName)
{
bool isSuccess = false;
bool isExistsAttribute = false;
XmlDocument xmlDoc = new XmlDocument();
try
{
xmlDoc.Load(xmlFileName); //加载XML文档
XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
XmlAttribute xmlAttribute = null;
if (xmlNode != null)
{
//遍历xpath节点中的所有属性
foreach (XmlAttribute attribute in xmlNode.Attributes)
{
if (attribute.Name.ToLower() == xmlAttributeName.ToLower())
{
//节点中存在此属性
xmlAttribute = attribute;
isExistsAttribute = true;
break;
}
}
if (isExistsAttribute)
{
//删除节点中的属性
xmlNode.Attributes.Remove(xmlAttribute);
}
}
xmlDoc.Save(xmlFileName); //保存到XML文档
isSuccess = true;
}
catch (Exception ex)
{
throw ex; //这里可以定义你自己的异常处理
}
return isSuccess;
}
/// <summary>
/// 删除匹配XPath表达式的第一个节点中的所有属性
/// </summary>
/// <param name="xmlFileName">XML文档完全文件名(包含物理路径)</param>
/// <param name="xpath">要匹配的XPath表达式(例如:"//节点名//子节点名</param>
/// <returns>成功返回true,失败返回false</returns>
public static bool DeleteAllXmlAttributeByXPath(string xmlFileName, string xpath)
{
bool isSuccess = false;
XmlDocument xmlDoc = new XmlDocument();
try
{
xmlDoc.Load(xmlFileName); //加载XML文档
XmlNode xmlNode = xmlDoc.SelectSingleNode(xpath);
if (xmlNode != null)
{
//遍历xpath节点中的所有属性
xmlNode.Attributes.RemoveAll();
}
xmlDoc.Save(xmlFileName); //保存到XML文档
isSuccess = true;
}
catch (Exception ex)
{
throw ex; //这里可以定义你自己的异常处理
}
return isSuccess;
}
#endregion
}
}
------------------------------------------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.IO;
using System.Data;
namespace JasonT.XML.pages
{
public partial class Default : System.Web.UI.Page
{
static DataSet ds = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string sFile = this.txtFileName.Text;
if (sFile != null)
{
DataTable dt = ReadTXTFile(sFile);
ds.Tables.Add(dt);
//DataView dv = dt.DefaultView;
//dv.Sort = "a0 desc";
this.GridView1.DataSource = dt;
this.GridView1.DataBind();
}
}
/// <summary>
/// 读取txt文件到datatable
/// </summary>
/// <param name="sTxtFilePath"></param>
/// <returns></returns>
public DataTable ReadTXTFile(string sTxtFilePath)
{
FileStream fs = new FileStream(sTxtFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
StreamReader sr = new StreamReader(fs);
sr.BaseStream.Seek(0, SeekOrigin.Begin);
string str = sr.ReadLine();
string[] sArr = str.Split('|');
DataTable dt = new DataTable();
for (int i = 0; i < sArr.Length; i++)
{
dt.Columns.Add("a" + i, Type.GetType("System.String"));
}
while (str != null)
{
string[] strs = str.Split('|');
DataRow dr = null;
dr = dt.NewRow();
for (int i = 0; i < strs.Length; i++)
{
dr[i] = strs[i];
}
dt.Rows.Add(dr);
//Response.Write(str);
str = sr.ReadLine();
}
sr.Close();
fs.Close();
return dt;
}
/// <summary>
/// 转换xml到dataset
/// </summary>
/// <param name="xmlStr"></param>
/// <returns></returns>
public static DataSet ConvertXMLToDataSet(string xmlStr)
{
DataSet ds = new DataSet();
if (!string.IsNullOrEmpty(xmlStr))
{
StringReader sReder = null;
XmlTextReader xmlReader = null;
try
{
sReder = new StringReader(xmlStr);
xmlReader = new XmlTextReader(sReder);
ds.ReadXml(xmlReader);
}
catch (Exception ex) { throw ex; }
}
return ds;
}
/// <summary>
/// 转换XML到DATASET
/// </summary>
/// <param name="xmlFile"></param>
/// <returns></returns>
public DataSet ConvertXMLFileToDataSet(string xmlFile)
{
DataSet ds = new DataSet();
StringReader stringReader = null;
XmlTextReader xmlReader = null;
try
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(xmlFile);
stringReader = new StringReader(xmldoc.InnerXml);
xmlReader = new XmlTextReader(stringReader);
ds.ReadXml(xmlReader);
return ds;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (stringReader != null)
stringReader.Close();
}
}
/// <summary>
/// 转换DATASET到XML
/// </summary>
/// <param name="xmlDS"></param>
/// <param name="xmlFile"></param>
private static void ConvertDataSetToXMLFile(DataSet xmlDS, string xmlFile)
{
int ii = xmlDS.Tables[0].Rows.Count;
MemoryStream stream = null;
XmlTextWriter writer = null;
try
{
stream = new MemoryStream();
//从stream装载到XmlTextReader
writer = new XmlTextWriter(stream, System.Text.Encoding.Unicode);
//用WriteXml方法写入文件.
xmlDS.WriteXml(writer);
int count = (int)stream.Length;
byte[] arr = new byte[count];
stream.Seek(0, SeekOrigin.Begin);
stream.Read(arr, 0, count);
//返回Unicode编码的文本
System.Text.UnicodeEncoding utf = new System.Text.UnicodeEncoding();
StreamWriter sw = new StreamWriter(xmlFile);
sw.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
sw.WriteLine(utf.GetString(arr).Trim());
sw.Flush();
sw.Close();
}
catch (System.Exception ex)
{
throw ex;
}
finally
{
if (writer != null) writer.Close();
}
}
static string file = "";
static string path = "";
protected void Button2_Click(object sender, EventArgs e)
{
file = "/xml" + DateTime.Now.ToString("MMdd") + ".XML";
path = Server.MapPath("xmlfile") + file;
Response.Write(path);
ConvertDataSetToXMLFile(ds, path);
}
protected void Button3_Click(object sender, EventArgs e)
{
Response.Redirect("xmlfile" + file);
}
protected void Button4_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds = ConvertXMLFileToDataSet(path);
this.GridView1.DataSource = ds.Tables[0];
this.GridView1.DataBind();
}
/// <summary>
/// 添加节点
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Button5_Click(object sender, EventArgs e)
{
string a1 = this.txt1.Text;
string a2 = this.txt2.Text;
string a3 = this.txt3.Text;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(path);
XmlNode root = xmlDoc.SelectSingleNode("NewDataSet");//查找
XmlElement xe1 = xmlDoc.CreateElement("Table1");//创建一个节点
XmlElement xesub1 = xmlDoc.CreateElement("a0");
xesub1.InnerText = a1;//设置文本节点
xe1.AppendChild(xesub1);//添加到节点中
XmlElement xesub2 = xmlDoc.CreateElement("a1");
xesub2.InnerText = a2;
xe1.AppendChild(xesub2);
XmlElement xesub3 = xmlDoc.CreateElement("a2");
xesub3.InnerText = a3;
xe1.AppendChild(xesub3);
root.AppendChild(xe1);//添加到节点中
xmlDoc.Save(path);
}
/// <summary>
/// 删除信息jiedian
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Button6_Click(object sender, EventArgs e)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(path);
XmlNodeList nodeList = xmlDoc.SelectSingleNode("NewDataSet").ChildNodes;//获取bookstore节点的所有子节点
foreach (XmlNode item in nodeList)
{
XmlElement xe = (XmlElement)item;//将子节点类型转换为XmlElement类型
XmlNodeList nls = xe.ChildNodes;//继续获取xe子节点的所有子节点
foreach (XmlNode xn1 in nls)//遍历
{
string s = xn1.InnerXml;
string name = xn1.Name;
if (name == "a0")
{
if (xn1.InnerText == this.txt1.Text)
{
XmlNode newnode = xn1.ParentNode;
newnode.ParentNode.RemoveChild(newnode);
}
}
}
}
xmlDoc.Save(path);//保存。
//XmlDocument xmlDoc = new XmlDocument();
//xmlDoc.Load(path);
//XmlNodeList xnl = xmlDoc.SelectSingleNode("NewDataSet").ChildNodes;
//foreach (XmlNode xn in xnl)
//{
// XmlElement xe = (XmlElement)xn;
// if (xe.GetAttribute("genre") == "fantasy")
// {
// xe.RemoveAttribute("genre");//删除genre属性
// }
// else if (xe.GetAttribute("genre") == "update李赞红")
// {
// xe.RemoveAll();//删除该节点的全部内容
// }
//}
//xmlDoc.Save(path);
}
/// <summary>
/// 修改节点
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Button7_Click(object sender, EventArgs e)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(path);
XmlNodeList nodeList = xmlDoc.SelectSingleNode("NewDataSet").ChildNodes;//获取bookstore节点的所有子节点
foreach (XmlNode item in nodeList)
{
XmlElement xe = (XmlElement)item;//将子节点类型转换为XmlElement类型
XmlNodeList nls = xe.ChildNodes;//继续获取xe子节点的所有子节点
foreach (XmlNode xn1 in nls)//遍历
{
string s = xn1.InnerXml;
string name = xn1.Name;
if (name == "a0")
{
if (xn1.InnerText == this.txt1.Text)
{
XmlNode newnode = xn1.ParentNode;
//newnode.RemoveAll();
newnode.ChildNodes[1].InnerText = this.txt2.Text;
newnode.ChildNodes[2].InnerText = this.txt3.Text;
}
}
}
}
xmlDoc.Save(path);//保存。
}
}
}