首页 > 代码库 > 创建Xml的将但方法和向Xml中添加数据

创建Xml的将但方法和向Xml中添加数据

 1 想要的Xml样式
 2 <Root>
 3   <Cast>
 4     <SendUserId>3</SendUserId>
 5     <Title>asdafdf</Title>
 6     <Content>sadggdfaf</Content>
 7     <DateTime>2014/8/30 18:11:23</DateTime>
 8     <ListUser>
 9       <AcceptUserId>42</AcceptUserId>
10       <AcceptUserId>43</AcceptUserId>
11     </ListUser>
12   </Cast>
13 </Root>
14 
15 C#代码
16 /// <summary>
17         /// 创建Xml文件
18         /// </summary>
19         /// <param name="userId">接收人的id</param>
20         /// <param name="title">标题</param>
21         /// <param name="content">内容</param>
22         public static void CreateXML(string userId, string title, string content)
23         {
24             XmlDocument xmldoc = new XmlDocument();
25             XmlNode xmlnode = xmldoc.CreateXmlDeclaration("1.0""utf-8"null);
26             xmldoc.AppendChild(xmlnode);
27             //创建根节点
28             XmlElement xmlroot = xmldoc.CreateElement("Root");
29 
30 
31             //创建一级节点
32             XmlElement xmlcast = xmldoc.CreateElement("Cast");
33             xmlroot.AppendChild(xmlcast);
34             //创建二级节点及其平行节点
35             XmlElement xmlsend = xmldoc.CreateElement("SendUserId");
36             xmlsend.InnerText = WangCaiConfig.User.Id.ToString();
37             xmlcast.AppendChild(xmlsend);
38 
39             XmlElement xmlsubject = xmldoc.CreateElement("Title");
40             xmlsubject.InnerText = title;
41             xmlcast.AppendChild(xmlsubject);
42 
43             XmlElement xmlcontent = xmldoc.CreateElement("Content");
44             xmlcontent.InnerText = content;
45             xmlcast.AppendChild(xmlcontent);
46 
47             XmlElement xmltime = xmldoc.CreateElement("DateTime");
48             xmltime.InnerText = DateTime.Now.ToString();
49             xmlcast.AppendChild(xmltime);
50 
51             //创建三级节点
52             XmlElement xmllist = xmldoc.CreateElement("ListUser");
53             xmlcast.AppendChild(xmllist);
54 
55             string[] userIdList = userId.Split(&);
56             for (int i = 0; i < userIdList.Length - 1; i++)
57             {
58                 //创建四级节点及其平行节点
59                 XmlElement xmlAcceptId = xmldoc.CreateElement("AcceptUserId");
60                 xmlAcceptId.InnerText = userIdList[i].ToString();
61                 xmllist.AppendChild(xmlAcceptId);
62             }
63             //绑定根节点
64             xmldoc.AppendChild(xmlroot);
65             xmldoc.Save(WangCaiConfig.GetCurrentDirectory() + "UserXML/BoradCast.xml");
View CodeView Code

创建Xml的将但方法和向Xml中添加数据