• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
:皒祗想自私旳占有著袮
.Net Ajax SQLserver Flex UI JS 一样都不能少...
博客园    首页    新随笔    联系   管理    订阅  订阅

XmlDocument的应用---创建Xml模板 (转)

protected void btnCreate_Click(object sender, EventArgs e)
        
{
            
//定义XMLDocument
            XmlDocument xmlDocument = new XmlDocument();

            
//定义XML文档头文件
            XmlDeclaration xmlDeclaration = xmlDocument.CreateXmlDeclaration("1.0", "utf-8", null);
            
//增加XML文档头
            xmlDocument.AppendChild(xmlDeclaration);

            
//定义XML的根
            XmlElement xmlRoot = xmlDocument.CreateElement("Roots");
            
//添加XML的根
            xmlDocument.AppendChild(xmlRoot);

            
//添加根的属性
            xmlRoot.SetAttribute("RootAttribute", "Value");

            
//修改根属性的值
            xmlRoot.GetAttributeNode("RootAttribute").Value = "FixValue";

            
//定义节点
            XmlNode xmlElement;

            
//循环创建节点
            for (int i = 0; i < 2; i++)
            
{
                
//创建XML根的节点
                xmlElement = xmlDocument.CreateElement("Element");

                
//XML需要的属性列表
                foreach (KeyValuePair<String, String> keyValuePair in NameValueDictionary())
                
{
                    
//定义XML根的节点中的属性
                    XmlAttribute oneAttribute = xmlDocument.CreateAttribute(keyValuePair.Key);
                    oneAttribute.Value 
= keyValuePair.Value;

                    XmlAttribute secAttribute 
= xmlDocument.CreateAttribute(keyValuePair.Key);
                    secAttribute.Value 
= keyValuePair.Value;

                    
//添加XML根的节点中的属性
                    xmlElement.Attributes.Append(oneAttribute);
                    xmlElement.Attributes.Append(secAttribute);

                    
//添加XML根的节点
                    xmlRoot.AppendChild(xmlElement);
                }

            }

            
//保存XML文档
            xmlDocument.Save(Server.MapPath("OutDocument.XML"));
        }


        
//XML需要的属性列表
        private Dictionary<String, String> NameValueDictionary()
        
{
            Dictionary
<String, String> nameValueDictionary = new Dictionary<String, String>();

            nameValueDictionary.Add(
"AttributeOne", "One");
            nameValueDictionary.Add(
"AttributeSec", "Second");

            
return nameValueDictionary;
        }


生成的XML模块

<?xml version="1.0" encoding="utf-8"?>
<Roots RootAttribute="FixValue">
  
<Element AttributeOne="One" AttributeSec="Second" />
  
<Element AttributeOne="One" AttributeSec="Second" />
</Roots>
posted @ 2008-03-04 16:57  JoyBin  阅读(785)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3