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);
  • 相关阅读:
    Hadoop2.2.0 注意事项
    为一个表增加一列,这个列能够自增加1
    商品推荐系统问题
    Android Service服务-(转)
    android实现通知栏消息
    【Android】状态栏通知Notification、NotificationManager详解(转)
    android调用邮件应用发送email
    有关WebView开发问题(转)
    Android开发把项目打包成apk-(转)
    对话框(单选)
  • 原文地址:https://www.cnblogs.com/pyffcwj/p/3328104.html
Copyright © 2011-2022 走看看