C#添加XmlNode节点 . 2012-02-23 13:28 1793人阅读 评论(0) 收藏 举报 c#stringexceptionnulldownloadencoding public void Load(XmlDocument foc2, int load, string load2, string load3, string load4) { XmlNode root = foc2.DocumentElement; // 二级节点 XmlNode node = Xmldoc.CreateElement("Flight"); XmlElement elemLoad = foc2.CreateElement("id"); elemLoad.InnerText = load2.ToString(); XmlElement elemLoad2 = foc2.CreateElement("bookseats"); elemLoad2.InnerText = load.ToString(); XmlElement elemLoad3 = foc2.CreateElement("departure"); elemLoad3.InnerText = load3.ToString(); XmlElement elemLoad4 = foc2.CreateElement("arrival"); elemLoad4.InnerText = load4.ToString(); node.AppendChild(elemLoad); node.AppendChild(elemLoad2); node.AppendChild(elemLoad3); node.AppendChild(elemLoad4); root.AppendChild(node); } ================================================================== 准备生成的XML文件格式以下: <?xml version="1.0" encoding="utf-8" ?> <Update> <Soft Name="BlogWriter"> <Verson>1.0.1.2</Verson> <DownLoad>http://www.csdn.net/BlogWrite.rar</DownLoad> </Soft> </Update> 详细代码为: XmlDocument doc = new XmlDocument(); XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null); doc.AppendChild(dec); //建立一个根节点(一级) XmlElement root = doc.CreateElement("Update"); doc.AppendChild(root); //建立节点(二级) XmlNode node = doc.CreateElement("Soft"); node.Attributes.Append(CreateAttribute(node, "Name", "BlogWriter")); //建立节点(三级) XmlElement element1 = doc.CreateElement("Verson"); element1.InnerText = "1.0.1.2"; node.AppendChild(element1); XmlElement element2 = doc.CreateElement("DownLoad"); element2.InnerText = "http://www.csdn.net/BlogWrite.rar"; node.AppendChild(element2); root.AppendChild(node); doc.Save(@"C:\web\bb.xml"); Console.Write(doc.OuterXml); 添加节点属性方法 public XmlAttribute CreateAttribute(XmlNode node, string attributeName, string value) { try { XmlDocument doc = node.OwnerDocument; XmlAttribute attr = null; attr = doc.CreateAttribute(attributeName); attr.Value = value; node.Attributes.SetNamedItem(attr); return attr; } catch (Exception err) { string desc = err.Message; return null; } } 须要添加的命名空间为using System.Xml;