zoukankan      html  css  js  c++  java
  • C# XML操作

    1.XML帮助类

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Xml;
    using System.Data.SqlClient;
    using System.Data;
    using System.IO;
    using System.Xml.Serialization;
    
    namespace AutoO2O.Common
    {
        public class XmlHelper : XmlDocument
        {
            public string filePath = string.Empty;      
    
            public XmlHelper()
            {
    
            }
    
            public XmlHelper(string FilePath)
            {
                this.filePath = FilePath;
                this.Load(FilePath);
            }
    
            /// <summary>
            /// 创建根
            /// </summary>
            /// <param name="RootNodeName"></param>
            public void NewDocument(string RootNodeName)
            {
                XmlElement root = this.CreateElement(RootNodeName);
                this.AppendChild(root);
            }
    
            /// <summary>
            /// 新建一个节点
            /// </summary>
            /// <param name="Name"></param>
            /// <param name="Value"></param>
            /// <returns></returns>
            public XmlNode NewNode(XmlNode parent, string Name, string Value)
            {
                XmlNode node = this.CreateNode(XmlNodeType.Element, Name, "");
                XmlNode node1 = this.CreateNode(XmlNodeType.Text, Name, "");
                node1.Value = Value;
    
                node.AppendChild(node1);
    
                parent.AppendChild(node);
    
                return node;
            }
    
            /// <summary>
            /// 新建一个节点
            /// </summary>
            /// <param name="Name"></param>
            /// <param name="Value"></param>
            /// <param name="MyType"></param>
            /// <returns></returns>
            public XmlNode NewNode(XmlNode parent, string Name, string Value, XmlNodeType MyType)
            {
                XmlNode node = this.CreateNode(XmlNodeType.Element, Name, "");
                XmlNode node1 = this.CreateNode(MyType, Name, "");
                node1.Value = Value;
    
                node.AppendChild(node1);
                parent.AppendChild(node);
    
                return node;
            }
    
            /// <summary>
            /// 新建多个节点
            /// </summary>
            /// <param name="parent"></param>
            /// <param name="data"></param>
            public void NewNode(XmlNode parent, Dictionary<string, string> data)
            {
                foreach (string key in data.Keys)
                {
                    XmlNode node = this.CreateNode(XmlNodeType.Element, key, "");
                    XmlNode node1 = this.CreateNode(XmlNodeType.Text, key, "");
                    node1.Value = data[key];
    
                    node.AppendChild(node1);
    
                    parent.AppendChild(node);
                }
            }
    
            /// <summary>
            /// 新建多个节点
            /// </summary>
            /// <param name="parent"></param>
            /// <param name="data"></param>
            public void NewNode(XmlNode parent, Dictionary<string, string> data, XmlNodeType MyType)
            {
                foreach (string key in data.Keys)
                {
                    XmlNode node = this.CreateNode(XmlNodeType.Element, key, "");
                    XmlNode node1 = this.CreateNode(MyType, key, "");
                    node1.Value = data[key];
    
                    node.AppendChild(node1);
    
                    parent.AppendChild(node);
                }
            }
    
            /// <summary>
            /// 新建多个节点,并添加属性
            /// </summary>
            /// <param name="parent"></param>
            /// <param name="data"></param>
            public void NewNode(XmlNode parent, Dictionary<string, string> data, List<Dictionary<string, string>> attributes)
            {
                int i = 0;
                foreach (string key in data.Keys)
                {
                    XmlNode node = this.CreateNode(XmlNodeType.Element, key, "");
                    XmlNode node1 = this.CreateNode(XmlNodeType.Text, key, "");
                    node1.Value = data[key];
    
                    node.AppendChild(node1);
    
                    Dictionary<string, string> attr = attributes[i++];
                    this.NewAttributes(node, attr);
    
                    parent.AppendChild(node);
                }
            }
    
            /// <summary>
            /// 添加属性
            /// </summary>
            /// <param name="parent"></param>
            /// <param name="Name"></param>
            /// <param name="Value"></param>
            public void NewAttributes(XmlNode parent, string Name, string Value)
            {
                XmlAttribute attr = this.CreateAttribute(Name);
                attr.Value = Value;
    
                parent.Attributes.Append(attr);
            }
    
            /// <summary>
            /// 添加属性
            /// </summary>
            /// <param name="parent"></param>
            /// <param name="Name"></param>
            /// <param name="Value"></param>
            public void NewAttributes(XmlNode parent, Dictionary<string, string> data)
            {
                foreach (string key in data.Keys)
                {
                    XmlAttribute attr = this.CreateAttribute(key);
                    attr.Value = data[key];
    
                    parent.Attributes.Append(attr);
                }
            } 
    
            /// <summary>
            /// 返回数据集
            /// </summary>
            /// <returns></returns>
            public DataSet getDataSet()
            {
                DataSet ds = new DataSet();
                XmlNodeReader xnr = new XmlNodeReader(this);
                ds.ReadXml(xnr);
                if (ds.Tables.Count == 0)
                    return null;
    
                return ds;
            }
    
            /// <summary>
            /// 节点转DataSet
            /// </summary>
            /// <param name="node"></param>
            /// <returns></returns>
            public DataSet ConvertToDataSet(XmlNode node)
            {
                if (node == null) return null;
                DataSet ds = new DataSet();
                XmlNodeReader xnr = new XmlNodeReader(node);
                ds.ReadXml(xnr);
                return ds;
            }
    
            #region 序列化XML文件
            /// <summary> 
            /// 序列化XML文件 
            /// </summary> 
            /// <param name="type">类型</param> 
            /// <param name="obj">对象</param> 
            /// <returns></returns> 
            public static string Serializer(Type type, object obj)
            {
                MemoryStream Stream = new MemoryStream();
    
                //创建序列化对象 
                XmlSerializer xml = new XmlSerializer(type);
                try
                {
                    //序列化对象 
                    xml.Serialize(Stream, obj);
                }
                catch (InvalidOperationException)
                {
                    throw;
                }
    
                Stream.Position = 0;
                StreamReader sr = new StreamReader(Stream);
                string str = sr.ReadToEnd();
    
                return str;
            }
            #endregion
    
            #region 反序列化
            /// <summary> 
            /// 反序列化 
            /// </summary> 
            /// <param name="type">类型</param> 
            /// <param name="xml">XML字符串</param> 
            /// <returns></returns> 
            public static object Deserialize(Type type, string xml)
            {
                try
                {
                    using (StringReader sr = new StringReader(xml))
                    {
                        XmlSerializer xmldes = new XmlSerializer(type);
                        return xmldes.Deserialize(sr);
                    }
                }
                catch (Exception e)
                {
                    return null;
                }
            }
            #endregion
        }
    }

    2.Demo

    static void Main(string[] args)
            {
                List<string> tempArray = new List<string>() { "孔明", "子龙", "CallmeYhz" };
    
                //创建XML字符串
                AutoO2O.Common.XmlHelper xmlHelper = new AutoO2O.Common.XmlHelper();
                xmlHelper.NewDocument("Items");          
    
                tempArray.ForEach((string str) =>
                {
                    var node = xmlHelper.NewNode(xmlHelper.FirstChild, "Item", "");
                    xmlHelper.NewAttributes(node, "Name", str);
                });
    
                //得到XML字符串
                string xmlStr = xmlHelper.OuterXml;
                Console.WriteLine("转化后的XML字符串为:"+xmlStr);
                Console.WriteLine("****************************************************************");
                string ids = string.Empty;
                //将XML字符串还原成元素
                xmlHelper.LoadXml(xmlStr);
         
                foreach (XmlNode item in xmlHelper.FirstChild.ChildNodes)
                {          
                    ids += item.Attributes["Name"].Value + ",";
                }
                Console.WriteLine("还原后的元素为:"+ids);
                Console.ReadKey();
    
    
    
            }

    3.结果

  • 相关阅读:
    Makefile笔记
    GUN详解
    学习SDL
    [翻译]在ASP.NET MVC中使用TDD与依赖注入
    ASP.NET MVC Preview 3 STEP BY STEP 文章管理实例(二)
    一个小Forum Web程序示例,ASP.NET MVC Framework,TDD简介(Part 2)
    一个小Forum Web程序示例,ASP.NET MVC Framework,总体结构介绍(Part 1)
    ASP.NET MVC Preview 4 源代码学习笔记 FilterAttribute
    在ASP.NET MVC Framework 中执行简单验证(翻的)
    一个小Forum Web程序示例,SqlForumRepository,LazyList和PagedList(Part 3)
  • 原文地址:https://www.cnblogs.com/CallmeYhz/p/6405899.html
Copyright © 2011-2022 走看看