zoukankan      html  css  js  c++  java
  • C#中的XML文件操作(一)

    Create a New XML File Using XmlDocument

    Here's the XML File:

    1 <?xml version="1.0" encoding="utf-8"?>
    2 <CategoryList>
    3   <Category ID="01">
    4     <MainCategory>XML</MainCategory>
    5     <Description>This is a list my XML articles.</Description>
    6     <Active>true</Active>
    7   </Category>
    8 </CategoryList>

    Here's the code:

     1 XmlDocument xmlDoc = new XmlDocument();
     2 
     3 
     4         // Write down the XML declaration
     5         XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0","utf-8",null); 
     6 
     7         // Create the root element
     8         XmlElement rootNode  = xmlDoc.CreateElement("CategoryList");
     9         xmlDoc.InsertBefore(xmlDeclaration, xmlDoc.DocumentElement); 
    10         xmlDoc.AppendChild(rootNode);
    11 
    12         // Create a new <Category> element and add it to the root node
    13         XmlElement parentNode  = xmlDoc.CreateElement("Category");
    14 
    15         // Set attribute name and value!
    16         parentNode.SetAttribute("ID", "01");
    17 
    18         xmlDoc.DocumentElement.PrependChild(parentNode);
    19 
    20         // Create the required nodes
    21         XmlElement mainNode  = xmlDoc.CreateElement("MainCategory");
    22         XmlElement descNode  = xmlDoc.CreateElement("Description");
    23         XmlElement activeNode  = xmlDoc.CreateElement("Active");
    24 
    25         // retrieve the text 
    26         XmlText categoryText= xmlDoc.CreateTextNode("XML");
    27         XmlText descText  = xmlDoc.CreateTextNode("This is a list my XML articles.");
    28         XmlText activeText  = xmlDoc.CreateTextNode("true");
    29 
    30         // append the nodes to the parentNode without the value
    31         parentNode.AppendChild(mainNode);
    32         parentNode.AppendChild(descNode);
    33         parentNode.AppendChild(activeNode);
    34 
    35         // save the value of the fields into the nodes
    36         mainNode.AppendChild(categoryText);
    37         descNode.AppendChild(descText);
    38         activeNode.AppendChild(activeText);
    39 
    40         // Save to the XML file
    41         xmlDoc.Save( Path);
  • 相关阅读:
    JAVA查询树结构数据(省市区)使用hutool工具实现
    定时器
    工作队列
    中断类型
    通过风扇FG脚检测风扇转速
    共享中断
    Linux中断信号的查看
    使用Alibaba Cloud Linux 2系统开突发型实例遇到宿主机一直超分案例
    React学习(三)----- 组件的生命周期
    React学习(二)----- 面向组件编程
  • 原文地址:https://www.cnblogs.com/pyffcwj/p/3328104.html
Copyright © 2011-2022 走看看