您的位置:首页 > 编程语言 > C#

C#之XML基础 为一个节点添加两个属性值

2017-10-30 16:16 267 查看
1、代码

[csharp] view
plain copy

using System;  

using System.Collections.Generic;  

using System.Linq;  

using System.Text;  

using System.Threading.Tasks;  

using System.Xml;  

  

namespace ConsoleApplication3  

{  

    class Program  

    {  

        static void Main(string[] args)  

        {  

            XmlDocument xml = new XmlDocument();  

  

            //创建第一行描述信息  

            //                                                       版本   编码格式    

            XmlDeclaration theFirstRowOfXml=  xml.CreateXmlDeclaration("1.0","utf-8",null);  

            xml.AppendChild(theFirstRowOfXml);  

  

            //保存之前要创建根节点,根节点的名字是Books  

            XmlElement Books= xml.CreateElement("Books");  

            //再把创建的根节点加入到xml中  

            xml.AppendChild(Books);  

  

            //创建Books根节点下的一个子节点  

            XmlElement Book1 = xml.CreateElement("Book");  

            Books.AppendChild(Book1);  

  

            XmlElement Name = xml.CreateElement("Name");  

            Name.InnerText = "金刚经";  

            Book1.AppendChild(Name);  

  

            XmlElement Class = xml.CreateElement("Class");  

            Class.InnerText ="佛家";  

            Book1.AppendChild(Class);  

  

            XmlElement Count = xml.CreateElement("Count");  

            Count.SetAttribute("count", "10");  

            Count.SetAttribute("discount","80%");  

            Book1.AppendChild(Count);  

  

            xml.Save("创建的文件.xml");  

            Console.WriteLine("OK");  

            Console.ReadKey();  

        }  

    }  

}  

2、控制台效果



3、XML文件

[csharp] view
plain copy

<?xml version="1.0" encoding="utf-8"?>  

<Books>  

  <Book>  

    <Name>金刚经</Name>  

    <Class>佛家</Class>  

    <Count count="10" discount="80%" />  

  </Book>  

</Books>  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: