一聚教程网:一个值得你收藏的教程网站

热门教程

asp.net xml操作方法与xml操作类

时间:2022-06-25 06:34:32 编辑:袖梨 来源:一聚教程网

程序生成XML文档
这种方式是用 C# 程序生成一个 XML 文件,并将数据放在其中来处理。下面是几种不同的方法实现了同样的目的。

用XmlWriter类编辑数据而实现的简单示例:

 代码如下 复制代码
XmlTextWriter xtw = new XmlTextWriter(filePath, Encoding.UTF8);
xtw.Formatting = Formatting.Indented;
xtw.WriteStartDocument(true);
xtw.WriteStartElement("root");
xtw.WriteElementString("username", Nodevalue);
xtw.WriteEndElement();
xtw.WriteEndDocument();
xtw.Flush();
xtw.Close();

在示例代码中,Nodevalue 为所取得的数据值,代码略。filePath 为XML文件路径值,代码略。

运行结果是生成了一个内容与之前的那篇贴文一样的 XML 文档。

用XmlDocument类实现的示例:

 代码如下 复制代码

XmlDocument xmldoc;
XmlDeclaration xmldecl;
XmlNode xmlnode;
XmlElement xmlelem;

xmldoc = new XmlDocument();
xmldecl = xmldoc.CreateXmlDeclaration("1.0", "gb2312", null);
xmldoc.AppendChild(xmldecl);
xmlelem = xmldoc.CreateElement("", "root", "");
xmldoc.AppendChild(xmlelem);
xmlnode = xmldoc.CreateElement("username");
xmlnode.InnerText = Nodevalue;
xmlelem.AppendChild(xmlnode);
xmldoc.Save(filePath);

注意:因为XmlDocument类实现的话,与XmlWriter类实现相比,在性能上较低效些。所以推荐用XmlWriter类来实现。

用XML序列化的技术来实现:

 代码如下 复制代码
Root root = new Root();
root.Username = Nodevalue;
XmlSerializer srl = new XmlSerializer(typeof(Root));
StreamWriter wrt = new StreamWriter(filePath);
srl.Serialize(wrt, root);
wrt.Close();

下面是Root类的完整内容:

 代码如下 复制代码

using System;

public class Root
{
    private string _username;
    public string Username
    {
        get
        {
            return _username;
        }
        set
        {
            _username = value;
        }
    }
}

对已有的XML文档进行操作
如果是对已有的XML文档文件进行操作处理,而不是用程序来生成一个新的XML文档文件呢?下面的示例是C#编程代码部分片断:

 代码如下 复制代码
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(filePath);
XmlNodeList xmlnodelist = xmldoc.SelectSingleNode("Root").ChildNodes;
foreach (XmlNode xmlnode in xmlnodelist)
{
    while (xmlnode.Name == "Username")
    {
        xmlnode.InnerText = Nodevalue;
        break;
    }
}
xmldoc.Save(filePath);

代码是对已有XML文件进行操作处理的,那么,可以看看下面是类的构造方法中的程序示例:

 代码如下 复制代码
if (File.Exists(filePath))
{
    XmlOperateHandle();
}
else
{
    XmlWriterHandle();
}

为了改进程序的性能,那我们用XPathNavigator对象处理来修改重写:

 代码如下 复制代码

XmlDocument xmldoc = new XmlDocument();
try { xmldoc.Load(filePath); }
catch { }
XPathNavigator navigator = xmldoc.CreateNavigator();
navigator.MoveToRoot();
if(navigator.HasChildren)
{
    navigator.MoveToFirstChild();
    if (navigator.Name == "username")
    {
        navigator.InnerXml = Nodevalue;
    }
}

下面我们把xml写成一个类

 代码如下 复制代码

using System;
using System.Xml;
using System.Data;

namespace XmlClass
    {
        ///


        /// XML相关通用功能
        ///

        public class XmlHelper
        {
            public XmlHelper() { }

            ///


            /// XML资源类型
            ///

            public enum XmlType
            {
                File,
                String
            };

            #region 读取XML资源到DataSet中
            ///


            /// 读取XML资源到DataSet中
            ///

            /// XML资源,文件为路径,否则为XML字符串
            /// XML资源类型
            /// DataSet
            public static DataSet GetDataSet(string source, XmlType xmlType)
            {
                DataSet ds = new DataSet();
                if (xmlType == XmlType.File)
                {
                    ds.ReadXml(source);
                }
                else
                {
                    XmlDocument xd = new XmlDocument();
                    xd.LoadXml(source);
                    XmlNodeReader xnr = new XmlNodeReader(xd);
                    ds.ReadXml(xnr);
                }
                return ds;
            }

            #endregion

            #region 获取一个字符串xml文档中的ds
            ///


            /// 获取一个字符串xml文档中的ds
            ///

            /// 含有xml信息的字符串
            public static void get_XmlValue_ds(string xml_string, ref DataSet ds)
            {
                System.Xml.XmlDocument xd = new XmlDocument();
                xd.LoadXml(xml_string);
                XmlNodeReader xnr = new XmlNodeReader(xd);
                ds.ReadXml(xnr);
                xnr.Close();
                int a = ds.Tables.Count;
            }
            #endregion

            #region 读取XML资源到DataTable中
            ///


            /// 读取XML资源到DataTable中
            ///

            /// XML资源,文件为路径,否则为XML字符串
            /// XML资源类型:文件,字符串
            /// 表名称
            /// DataTable
            public static DataTable GetTable(string source, XmlType xmlType, string tableName)
            {
                DataSet ds = new DataSet();
                if (xmlType == XmlType.File)
                {
                    ds.ReadXml(source);
                }
                else
                {
                    XmlDocument xd = new XmlDocument();
                    xd.LoadXml(source);
                    XmlNodeReader xnr = new XmlNodeReader(xd);
                    ds.ReadXml(xnr);
                }
                return ds.Tables[tableName];
            }
            #endregion

            #region 读取XML资源中指定的DataTable的指定行指定列的值
            ///


            /// 读取XML资源中指定的DataTable的指定行指定列的值
            ///

            /// XML资源
            /// XML资源类型:文件,字符串
            /// 表名
            /// 行号
            /// 列名
            /// 值,不存在时返回Null
            public static object GetTableCell(string source, XmlType xmlType, string tableName, int rowIndex, string colName)
            {
                DataSet ds = new DataSet();
                if (xmlType == XmlType.File)
                {
                    ds.ReadXml(source);
                }
                else
                {
                    XmlDocument xd = new XmlDocument();
                    xd.LoadXml(source);
                    XmlNodeReader xnr = new XmlNodeReader(xd);
                    ds.ReadXml(xnr);
                }
                return ds.Tables[tableName].Rows[rowIndex][colName];
            }
            #endregion

            #region 读取XML资源中指定的DataTable的指定行指定列的值
            ///


            /// 读取XML资源中指定的DataTable的指定行指定列的值
            ///

            /// XML资源
            /// XML资源类型:文件,字符串
            /// 表名
            /// 行号
            /// 列号
            /// 值,不存在时返回Null
            public static object GetTableCell(string source, XmlType xmlType, string tableName, int rowIndex, int colIndex)
            {
                DataSet ds = new DataSet();
                if (xmlType == XmlType.File)
                {
                    ds.ReadXml(source);
                }
                else
                {
                    XmlDocument xd = new XmlDocument();
                    xd.LoadXml(source);
                    XmlNodeReader xnr = new XmlNodeReader(xd);
                    ds.ReadXml(xnr);
                }
                return ds.Tables[tableName].Rows[rowIndex][colIndex];
            }
            #endregion

            #region 将DataTable写入XML文件中
            ///


            /// 将DataTable写入XML文件中
            ///

            /// 含有数据的DataTable
            /// 文件路径
            public static void SaveTableToFile(DataTable dt, string filePath)
            {
                DataSet ds = new DataSet("Config");
                ds.Tables.Add(dt.Copy());
                ds.WriteXml(filePath);
            }
            #endregion

            #region 将DataTable以指定的根结点名称写入文件
            ///


            /// 将DataTable以指定的根结点名称写入文件
            ///

            /// 含有数据的DataTable
            /// 根结点名称
            /// 文件路径
            public static void SaveTableToFile(DataTable dt, string rootName, string filePath)
            {
                DataSet ds = new DataSet(rootName);
                ds.Tables.Add(dt.Copy());
                ds.WriteXml(filePath);
            }
            #endregion

            #region 使用DataSet方式更新XML文件节点
            ///


            /// 使用DataSet方式更新XML文件节点
            ///

            /// XML文件路径
            /// 表名称
            /// 行号
            /// 列名
            /// 更新值
            /// 更新是否成功
            public static bool UpdateTableCell(string filePath, string tableName, int rowIndex, string colName, string content)
            {
                bool flag = false;
                DataSet ds = new DataSet();
                ds.ReadXml(filePath);
                DataTable dt = ds.Tables[tableName];

                if (dt.Rows[rowIndex][colName] != null)
                {
                    dt.Rows[rowIndex][colName] = content;
                    ds.WriteXml(filePath);
                    flag = true;
                }
                else
                {
                    flag = false;
                }
                return flag;
            }
            #endregion

            #region 使用DataSet方式更新XML文件节点
            ///


            /// 使用DataSet方式更新XML文件节点
            ///

            /// XML文件路径
            /// 表名称
            /// 行号
            /// 列号
            /// 更新值
            /// 更新是否成功
            public static bool UpdateTableCell(string filePath, string tableName, int rowIndex, int colIndex, string content)
            {
                bool flag = false;

                DataSet ds = new DataSet();
                ds.ReadXml(filePath);
                DataTable dt = ds.Tables[tableName];

                if (dt.Rows[rowIndex][colIndex] != null)
                {
                    dt.Rows[rowIndex][colIndex] = content;
                    ds.WriteXml(filePath);
                    flag = true;
                }
                else
                {
                    flag = false;
                }
                return flag;
            }
            #endregion

            #region 读取XML资源中的指定节点内容
            ///


            /// 读取XML资源中的指定节点内容
            ///

            /// XML资源
            /// XML资源类型:文件,字符串
            /// 节点名称
            /// 节点内容
            public static object GetNodeValue(string source, XmlType xmlType, string nodeName)
            {
                XmlDocument xd = new XmlDocument();
                if (xmlType == XmlType.File)
                {
                    xd.Load(source);
                }
                else
                {
                    xd.LoadXml(source);
                }
                XmlElement xe = xd.DocumentElement;
                XmlNode xn = xe.SelectSingleNode("//" + nodeName);
                if (xn != null)
                {
                    return xn.InnerText;
                }
                else
                {
                    return null;
                }
            }

            ///


            /// 读取XML资源中的指定节点内容
            ///

            /// XML资源
            /// 节点名称
            /// 节点内容
            public static object GetNodeValue(string source, string nodeName)
            {
                if (source == null || nodeName == null || source == "" || nodeName == "" || source.Length < nodeName.Length * 2)
                {
                    return null;
                }
                else
                {
                    int start = source.IndexOf("<" + nodeName + ">") + nodeName.Length + 2;
                    int end = source.IndexOf("");
                    if (start == -1 || end == -1)
                    {
                        return null;
                    }
                    else if (start >= end)
                    {
                        return null;
                    }
                    else
                    {
                        return source.Substring(start, end - start);
                    }
                }
            }
            #endregion

            #region 更新XML文件中的指定节点内容
            ///


            /// 更新XML文件中的指定节点内容
            ///

            /// 文件路径
            /// 节点名称
            /// 更新内容
            /// 更新是否成功
            public static bool UpdateNode(string filePath, string nodeName, string nodeValue)
            {
                bool flag = false;

                XmlDocument xd = new XmlDocument();
                xd.Load(filePath);
                XmlElement xe = xd.DocumentElement;
                XmlNode xn = xe.SelectSingleNode("//" + nodeName);
                if (xn != null)
                {
                    xn.InnerText = nodeValue;
                    flag = true;
                }
                else
                {
                    flag = false;
                }
                return flag;
            }
            #endregion

            #region 操作xml文件中指定节点的数据
            ///


            /// 获得xml文件中指定节点的节点数据
            ///

            ///
            ///
            public static string GetNodeInfoByNodeName(string path, string nodeName)
            {
                string XmlString = "";
                XmlDocument xml = new XmlDocument();
                xml.Load(path);
                System.Xml.XmlElement root = xml.DocumentElement;
                System.Xml.XmlNode node = root.SelectSingleNode("//" + nodeName);
                if (node != null)
                {
                    XmlString = node.InnerText;
                }
                return XmlString;
            }
            #endregion
        }
    }

热门栏目