C#添加XmlNode節點

 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;


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章