C#.Net操作XML

1,读取Rss订阅XML文件:读取线上的XML

 using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
namespace XmlTest.com
{
    /// <summary>
    /// 获得线上的Rss信息 / XML格式的</br>
    /// 订阅信息
    /// </summary>
    public class LoadOnlineXml
    {
        private readonly string rssPath;
        private readonly string encoding;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="rssPath"> Rss地址 , 如 : http://news.163.com/special/00011K6L/rss_newstop.xml </param>
        /// <param name="encoding"> 此Rss的编码格式</param>
        public LoadOnlineXml(string rssPath , string encoding )
        {
            this.rssPath = rssPath;
            this.encoding = encoding;
        }
        /// <summary>
        /// 打印目标Rss
        /// </summary>
        public void writeRss()
        {
            WebClient web = new WebClient();
            Stream stream = web.OpenRead(this.rssPath);
            StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(this.encoding));
            string rssText = reader.ReadToEnd();
            Console.WriteLine(rssText);
            stream.Close();
            reader.Close();
        }
    }
}

2,读取XML

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace XmlTest.com
{
    /// <summary>
    /// 读取XML
    /// </summary>
    public class ReaderXml
    {
        private readonly string xmlPath;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="xmlPath">XML的地址</param>
        public ReaderXml(string xmlPath)
        {
            this.xmlPath = xmlPath;
        }
        /// <summary>
        /// 读XML信息
        /// </summary>
        public void readXML()
        {
            string str = "";
            XmlReader reader = XmlReader.Create( this.xmlPath );
            int i = 0 , j = 0;
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element)
                {
                    str += "节点名 : " + reader.Name
                        + Environment.NewLine;
                    str += ", 节点类型 : " + reader.NodeType
                        + Environment.NewLine;
                    str += ", 节点深度 : " + reader.Depth
                        + Environment.NewLine;
                    if (reader.HasAttributes) // 是否存在属性
                    {
                        for (i = 0, j = reader.AttributeCount; i < j; i += 1)
                        {
                            reader.MoveToAttribute(i);
                            str += " 属性 : " + reader.Name + " 值为 : " + reader.Value
                                + Environment.NewLine;
                        }
                    }
                }
                else if ( reader.NodeType == XmlNodeType.Text )
                {
                    if (reader.HasValue)  //是否存在文本值
                    {
                        str += ", 节点的文本值 : " + reader.Value
                            + Environment.NewLine;
                    }
                }
                else
                { 
                }
            }
            reader.Close();
            Console.WriteLine(str);
        }
    }
}

3,创建一个XML文件

 using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
namespace XmlTest.com
{
    /// <summary>
    /// 模拟没有xml的时候重建一个XML文件
    /// </summary>
    public class XmlWriterDefault
    {
        private readonly string xmlpath;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="xmlpath">xml路径</param>
        public XmlWriterDefault(string xmlpath)
        {
            this.xmlpath = xmlpath;
        }
        /// <summary>
        /// 编写一个基本的XML文件
        /// </summary>
        ///<param name="encoding"> 编码格式  </param>
        public void writerDefault( Encoding encoding )
        { 
            if ( !File.Exists( this.xmlpath ) )
            {
                XmlWriterSettings writer = new XmlWriterSettings();
                writer.Encoding = encoding;
                using( XmlWriter w = XmlWriter.Create( this.xmlpath , writer ))
                {
                    w.WriteStartElement("fristElement");
                    w.WriteAttributeString("name" , "Ainy");
                    w.WriteAttributeString("gender", "male");
                    w.WriteEndElement();
                    w.Flush();
                }
            }
        }
    }
}

4 , 核心操作

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace XmlTest.com
{
    /// <summary>
    /// 对XML信息的增,删,改
    /// </summary>
    public class XmlMainHandler
    {
        private readonly string xmlPath;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="xmlPath">目标XML的地址</param>
        public XmlMainHandler(string xmlPath)
        {
            this.xmlPath = xmlPath;
        }
        /// <summary>
        /// 增加一个属性
        /// </summary>
        /// <param name="name"> 属性名称 </param>
        /// <param name="value"> 属性值 </param>
        public void addAttribute(string name, string value , string targetName )
        {
            XmlDocument xdoc = new XmlDocument();
            xdoc.Load(this.xmlPath);
            foreach (XmlElement xElement in xdoc.DocumentElement.ChildNodes)
            {
                foreach (XmlElement xE in xElement.ChildNodes)
                {
                    Console.WriteLine("属性值 : " + xE.GetAttribute("name"));
                    if (xE.GetAttribute("name") == targetName)
                    {
                        XmlAttribute xA = xdoc.CreateAttribute(name);
                        xA.Value = value;
                        xE.Attributes.Append(xA);
                        break;
                    }
                }
            }
            xdoc.Save(this.xmlPath);
        }
        /// <summary>
        /// 删除一个属性
        /// </summary>
        /// <param name="AttributeName"></param>
        public void removeAttribute(string AttributeName)
        {
            XmlDocument xdoc = new XmlDocument();
            xdoc.Load(this.xmlPath);
            XmlNode targetNote = xdoc.SelectSingleNode(@"friends/friend/describe"); //!important : 第一次找到的friends/friend/describe , 如果没有找到,返回null
            if (targetNote != null)
            {
                // 定义一个属性
                if (targetNote.Attributes[AttributeName] != null)
                {
                    targetNote.Attributes.Remove(targetNote.Attributes[AttributeName]);
                }
                else
                {
                    Console.WriteLine("此节点没有'{0}'属性", AttributeName);
                }
            }
            else
            {
                Console.WriteLine("没有找到 friends/friend/describe 请检查");
            }
            xdoc.Save(this.xmlPath);
        }
        /// <summary>
        /// 修改一个属性
        /// </summary>
        /// <param name="AttributeName"></param>
        /// <param name="value"></param>
        public void editorAttribute(string AttributeName, string value)
        {
            XmlDocument xdoc = new XmlDocument();
            xdoc.Load(this.xmlPath);
            XmlNodeList targetList = xdoc.SelectNodes(@"friends/friend/base");
            foreach (XmlNode target in targetList)
            {
                if (target.Attributes[AttributeName] != null)
                {
                    if (target.Attributes[AttributeName].Value == "eisa")
                    {
                        target.Attributes[AttributeName].Value = "eisa-" + value;
                        target.InnerText = "XXX"; //加一个Text
                        xdoc.Save(this.xmlPath);
                        return;
                    }
                }
            }
            Console.WriteLine("修改属性 失败");
        }
    }
}

附件 : XML    friends.xml

 <?xml version="1.0" encoding="utf-8"?>
<friends>
  <friend>
    <base name="eisa-snow" tel="135244&&&" gender="female">XXX</base>
    <describe>my ---</describe>
  </friend>
  <friend>
    <base name="kawen" tel="13533449078" gender="male" 亲密度="80%" />
    <describe>my ****</describe>
  </friend>
</friends>

 

你可能感兴趣的:(xml,C#,net)