首页 > 学院 > 开发设计 > 正文

C#XmlTextWriter和XmlTextReader读写XML文件

2019-11-14 16:11:22
字体:
来源:转载
供稿:网友
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.xml;
 
namespace Xml
{
    class PRogram
    {
        static void Main(string[] args)
        {
            // XmlTextWriter 写文件
            XmlTextWriter writeXml = new XmlTextWriter(@c:MyXml.xml,Encoding.UTF8);
            writeXml.WriteStartDocument(false);
            writeXml.WriteStartElement(NetWork);
  
            writeXml.WriteComment(网络配置信息);
            writeXml.WriteStartElement(configration);
  
            writeXml.WriteElementString(ipAddress,192.168.2.168);
            writeXml.WriteElementString(Netmask, 255.255.255.0);
            writeXml.WriteElementString(Gateway, 202.103.24.68);
  
            writeXml.WriteEndElement();
            writeXml.WriteEndElement();
  
            writeXml.Flush();
            writeXml.Close();
 
 
            // XmlTextReader 读文件
            XmlTextReader readerXml = new XmlTextReader(@c:MyXml.xml);
            while(readerXml.Read())
            {
                if(readerXml.NodeType == XmlNodeType.Element)
                {
 
                    if(readerXml.Name == IpAddress)
                    {
                        Console.WriteLine(readerXml.ReadElementString().Trim());
                    }
                    if (readerXml.Name == Netmask)
                    {
                        Console.WriteLine(readerXml.ReadElementString().Trim());
                    }
                    if (readerXml.Name == Gateway)
                    {
                        Console.WriteLine(readerXml.ReadElementString().Trim());
                    }
                }
            }
            Console.ReadKey();
        }
    }
}

Xml文件内容:

/

控制台运行结果:

/


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表