C# 写入XML文档三种方法详细介绍

<?xml version="1.0" encoding="UTF-8"?> 
<Contacts> 
<Contact id="01"> 
<Name>Daisy Abbey</Name> 
<Gender>female</Gender> 
</Contact> 
</Contacts> 

若要实现以上xml文件,以下3种方法


1使用XmlDocument类

var xmlDoc = new XmlDocument(); 
//Create the xml declaration first 
xmlDoc.AppendChild(xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null)); 
//Create the root node and append into doc 
var el = xmlDoc.CreateElement("Contacts"); 
xmlDoc.AppendChild(el); 
// Contact 
XmlElement elementContact = xmlDoc.CreateElement("Contact"); 
XmlAttribute attrID = xmlDoc.CreateAttribute("id"); 
attrID.Value = "01"; 
elementContact.Attributes.Append(attrID); 
el.AppendChild(elementContact); 
// Contact Name 
XmlElement elementName = xmlDoc.CreateElement("Name"); 
elementName.InnerText = "Daisy Abbey"; 
elementContact.AppendChild(elementName); 
// Contact Gender 
XmlElement elementGender = xmlDoc.CreateElement("Gender"); 
elementGender.InnerText = "female"; 
elementContact.AppendChild(elementGender); 
xmlDoc.Save("test1.xml"); 

2.使用LINQ to XML 的XDocument类: 

方法一(XDocument)、

var doc = new XDocument( 
new XElement("Contacts", 
new XElement("Contact", 
new XAttribute("id", "01"), 
new XElement("Name", "Daisy Abbey"), 
new XElement("Gender", "female") 
) 
) 
); 
doc.Save("test2.xml"); 


方法二‘(XElement)、

        /// <summary>
        /// 2、添加元素
        /// </summary>
        /// <param name="xmlpath">XML文件的路径</param>
        private static void AddXmlElement(string xmlpath)
        {
            ///导入XML文件
            XElement xe = XElement.Load(xmlpath);
            ///创建一个新节点
            XElement book1 = new XElement("Book",
                               new XAttribute("BookID", "002"),
                               new XElement("BookNo", "0002"),
                               new XElement("BookName", "Book 0002"),
                               new XElement("BookPrice", "50"),
                               new XElement("BookRemark", "This is a book 0002")
                );
            ///添加节点到XML文件中,并保存
            xe.Add(book1);
            ///创建一个新节点
            XElement book2 = new XElement("Book",
                               new XAttribute("BookID", "003"),
                               new XElement("BookNo", "0003"),
                               new XElement("BookName", "Book 0003"),
                               new XElement("BookPrice", "30"),
                               new XElement("BookRemark", "This is a book 0003")
                );
            ///添加节点到XML文件中,并保存
            xe.Add(book2);
            ///创建一个新节点
            XElement book3 = new XElement("Book",
                               new XAttribute("BookID", "004"),
                               new XElement("BookNo", "0004"),
                               new XElement("BookName", "Book 0004"),
                               new XElement("BookPrice", "60"),
                               new XElement("BookRemark", "This is a book 0004")
                );
            ///添加节点到XML文件中
            xe.Add(book3);
            ///保存到XML文件中
            xe.Save(xmlpath);

            Console.WriteLine(xe);
        }
            //调用函数AddXmlElement(string xmlpath)
            ///添加XML元素
            Program.AddXmlElement(@"C:\BookStore.xml");


方法三(XEelemtnt)、
XElement el = XElement.Load(Server.MapPath("Data/Product.xml"));

XElement product = new XElement
(
    "Product",
    new XAttribute("ID", 2),
    new XElement("ProductName", "LINQ to Object"),
    new XElement("UnitPrice", 20m),
    new XElement("Remark", "")
);

el.Add(product);
el.Save(Server.MapPath("Data/Product.xml"));



3.使用XmlTextWriter类: 

String filename = String.Concat("test3.xml"); 
using (StreamWriter sw = new StreamWriter(filename)) 
{ 
// Create Xml Writer. 
XmlTextWriter xmlWriter = new XmlTextWriter(sw); 
// 也可以使用public XmlTextWriter(string filename, Encoding encoding)来构造 
// encoding默认为 UTF-8. 
//XmlTextWriter writer = new XmlTextWriter("test3.xml", null); 
// Set indenting so that its easier to read XML when open in Notepad and such apps. 
xmlWriter.Formatting = Formatting.Indented; 
// This will output the XML declaration 
xmlWriter.WriteStartDocument(); 
xmlWriter.WriteStartElement("Contacts"); 
xmlWriter.WriteStartElement("Contact"); 
xmlWriter.WriteAttributeString("id", "01"); 
xmlWriter.WriteElementString("Name", "Daisy Abbey"); 
xmlWriter.WriteElementString("Gender", "female"); 
// close contact </contact> 
xmlWriter.WriteEndElement(); 
// close contacts </contact> 
xmlWriter.WriteEndElement(); 
xmlWriter.WriteEndDocument(); 
xmlWriter.Close(); 
} 



  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C# XML文件读写操作源码,以及如何调用,注释详解,有任何问题请留言, 以下截取xml文件和部分调用代码段: * ++++++++++++++++++++++++++++++++++++++ <?xml version="1.0" encoding="utf-8" standalone="no"?> <!--TestPlugins的信息--> <!--DataPlugins的信息--> * ++++++++++++++++++++++++++++ xml xl = new xml(); xl.XMLWriteRootNode("info"); //XmlElement Eml1 = xl.XMLReadNode("",0); //XmlElement Eml2 = xl.XMLReadNode("DataPlugins", 1); //XmlElement Eml4 = xl.XMLReadNode("DeviceInfo", 2); // TestPlugins XmlElement testPlugins = xl.XMLCreateNode("TestPlugins", null, null); xl.XMLInsertNode("info", 0, "TestPlugins的信息", testPlugins); // FixturePlugin XmlElement fixturePlugin = xl.XMLCreateNode("TestPlugin", null, new Dictionary() { { "Type", "FixturePlugin" } }); xl.XMLInsertNode(testPlugins.LocalName, 1, null, fixturePlugin); // DUTPlugin XmlElement DUTPlugin = (XmlElement)fixturePlugin.CloneNode(true);// xl.XMLCreateNode("TestPlugin", null, new Dictionary() { { "Type", "DUTPlugin" } }); DUTPlugin.SetAttribute("Type", "DUTPlugin"); xl.XMLInsertNode(testPlugins.LocalName, 1, null, DUTPlugin); // Agilent34461APlugin XmlElement Agilent34461APlugin = xl.XMLCreateNode("TestPlugin", null, new Dictionary() { { "Type", "Agilent34461APlugin" } }); xl.XMLInsertNode(testPlugins.LocalName, 1, null, Agilent34461APlugin); // ================================== // DataPlugins XmlElement dataPlugins = xl.XMLCreateNode("DataPlugins", null, null); xl.XMLInsertNode("info", 0, "DataPlugins的信息", dataPlugins); // CSVLogPlugin XmlElement csvlogPlugin = xl.XMLCreateNode("DataPlugin", null, new Dictionary() { { "Type", "CSVLogPlugin" } }); xl.XMLInsertNode(dataPlugins.LocalName, 1, null, csvlogPlugin); XmlElement uartlogPlugin = (XmlElement)csvlogPlugin.CloneNode(true); uartlogPlugin.SetAttribute("Type", "UartLogPlugin"); xl.XMLInsertNode(dataPlugins.LocalName, 1, null, uartlogPlugin); XmlElement testlogPlugin = (XmlElement)csvlogPlugin.CloneNode(true); testlogPlugin.SetAttribute("Type", "TestLogPlugin"); xl.XMLInsertNode(dataPlugins.LocalName, 1, null, testlogPlugin); }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值