Home > Backend Development > XML/RSS Tutorial > XML (2) Write XML through XmlDocument and XDocument

XML (2) Write XML through XmlDocument and XDocument

黄舟
Release: 2017-02-10 16:28:58
Original
2215 people have browsed it

<pre name="code" class="plain">
Copy after login

XML can also be written in .net through XmlDocument and XDocument. XmlDocument is the standard XML writing class originally supported. Now the extended XDocument class is more convenient to use. Let’s use the XDocument class to write an XML file.

Writing steps:

(1) First create an XDocument object

(2) Set the XML document definition

(3) Create the root node

(4) Loop List collection creates child nodes (person class is used here to enter data)

(5) Save to file

<pre name="code" class="csharp"> List<person> list = new List<person>();
<span style="font-family:Microsoft YaHei;font-size:18px;">            
list.Add(new person() { name = "IstarI", age = 20, Email = "1061399756@qq.com" });
            list.Add(new person() { name = "Orange", age = 20, Email = "521@qq.com" });

            //1、创建一个XDocument对象
            XDocument xDoc = new XDocument();
            XDeclaration XDec = new XDeclaration("1.0", "utf-8","no");
            //设置xml的文档定义
            xDoc.Declaration = XDec;

            //2、创建根节点
            XElement rootElement = new XElement("List");
            xDoc.Add(rootElement);

            //3、循环list集合创建子节点
            for (int i = 0; i <list.Count; i++)
            {
                //为每个person对象创建一个person元素
                XElement xpersonElement = new XElement("person");
                xpersonElement.SetAttributeValue("id", (i + 1).ToString());
                xpersonElement.SetElementValue("name", list[i].name);
                xpersonElement.SetElementValue("age", list[i].age.ToString ());
                xpersonElement.SetElementValue("Email", list[i].Email);
                rootElement.Add(xpersonElement);
            }
            //4、保存到文件
            xDoc.Save("List1.xml");
            MessageBox.Show("OK");</span>
Copy after login


After writing is completed, this file will appear under Debug, and then open it You will see the results you want.

The above is the content of XML (2) written in XML through XmlDocument and XDocument. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

Related labels:
xml
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template