C#-XML基础 XDocument XElement 创建简单的xml文件

慈心积善融学习,技术愿为有情学。善心速造多好事,前人栽树后乘凉。我今于此写经验,愿见文者得启发。


  •    .NET Framework : 4.6.1
  •                           ide : visual studio 2017 community
  •                             os : win7 x86_64
  •            type setting : markdown
  •                         blog : https://blog.csdn.net/yushaopu
  •                     github : https://github.com/GratefulHeartCoder

code

using System;
using System.Xml.Linq;

namespace ConsoleApp
{

    class Program
    {
        static void Main(string[] args)
        {
            XDocument xmlFile = new XDocument();

            // 设置根元素
            XElement root = new XElement("cultures");

            // 子元素
            XElement taoists = new XElement("taoists");
            taoists.SetAttributeValue("count", "100");
            taoists.SetAttributeValue("comment", "good");

            XElement book1 = new XElement("book");
            book1.SetElementValue("name", "道德经");
            book1.SetElementValue("author", "老子");                                               
            XElement book2 = new XElement("book");
            book2.SetElementValue("name", "文始真经");
            book2.SetElementValue("author", "关尹子");

            taoists.Add(book1);
            taoists.Add(book2);

            root.Add(taoists);

            // 子元素
            XElement buddhism = new XElement("buddhism");
            buddhism.SetAttributeValue("count", "321");
            buddhism.SetAttributeValue("comment", "good");

            XElement book3 = new XElement("book");
            book3.SetElementValue("name", "金刚经");
            book3.SetElementValue("author", "释迦牟尼");

            XElement book4 = new XElement("book");
            book4.SetElementValue("name", "地藏菩萨本愿经");
            book4.SetElementValue("author", "地藏");

            buddhism.Add(book3);
            buddhism.Add(book4);

            root.Add(buddhism);

            // 根节点只能一个
            xmlFile.Add(root);
            // 保存文件
            xmlFile.Save("test.xml");

            Console.ReadKey();
        }
    }
}

xml file

<?xml version="1.0" encoding="utf-8"?>
<cultures>
  <taoists count="100" comment="good">
    <book>
      <name>道德经</name>
      <author>老子</author>
    </book>
    <book>
      <name>文始真经</name>
      <author>关尹子</author>
    </book>
  </taoists>
  <buddhism count="321" comment="good">
    <book>
      <name>金刚经</name>
      <author>释迦牟尼</author>
    </book>
    <book>
      <name>地藏菩萨本愿经</name>
      <author>地藏</author>
    </book>
  </buddhism>
</cultures>

resource


感恩曾经帮助过 心少朴 的人。
C#优秀,值得学习。
Console,WinForm,WPF,ASP.NET,Azure WebJob,WCF,Unity3d可以适当地了解一下。
XML,DTD,XMLSchema,XSL,SVG可以适当地了解一下。
注:此文是自学笔记所生,质量中下等,故要三思而后行。新手到此,不可照搬,应先研究其理象数,待能变通之时,自然跳出深坑。

猜你喜欢

转载自blog.csdn.net/yushaopu/article/details/81784470
今日推荐