文章出處
文章列表
下載路徑
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; namespace XMLOperation { class Program { //XPath獲取xml節點 static void Main(string[] args) { //CreateXml(@"D:\Test\Books.xml"); string path = @"..\..\upload"; string[] filenames = Directory.GetFiles(path); //獲取該文件夾下面的所有文件名 foreach (var item in filenames) { ReadXml(item); } } private static void CreateXml(string filePath) { //1、創建XML文檔對象 XmlDocument doc = new XmlDocument(); //2、創建第一個行描述信息,并且添加到doc文檔中 XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null); doc.AppendChild(dec); //3、創建根節點,將根節點添加到文檔中 XmlElement root = doc.CreateElement("Books"); doc.AppendChild(root); //4-1、給根節點創建子節點book1,將book1添加到根節點 XmlElement book1 = doc.CreateElement("Book"); root.AppendChild(book1); //4-2、給book1添加子節點 XmlElement book1Name = doc.CreateElement("Name"); book1Name.InnerText = "肖申克的救贖"; XmlElement book1Price = doc.CreateElement("Price"); book1Price.InnerText = "36.0"; XmlElement book1Author = doc.CreateElement("Author"); book1Author.InnerText = "斯蒂芬金"; book1.AppendChild(book1Name); book1.AppendChild(book1Price); book1.AppendChild(book1Author); //5-1、給根節點創建子節點book2,將book2添加到根節點 XmlElement book2 = doc.CreateElement("Book"); root.AppendChild(book2); //5-2、給book2添加子節點 XmlElement book2Name = doc.CreateElement("Name"); book2Name.InnerText = "白夜行"; XmlElement book2Price = doc.CreateElement("Price"); book2Price.InnerText = "24.0"; XmlElement book2Author = doc.CreateElement("Author"); book2Author.InnerText = "東野圭吾"; book2.AppendChild(book2Name); book2.AppendChild(book2Price); book2.AppendChild(book2Author); //5-3、給節點book2添加屬性——SetAttribute book2.SetAttribute("Id", "24"); book2.SetAttribute("Count", "16"); //6、保存xml到指定目錄,默認會覆蓋原文件 doc.Save(filePath); Console.WriteLine("創建{0}成功", filePath); } private static void ReadXml(string filePath) { //1、創建XML文檔對象 XmlDocument doc = new XmlDocument(); //2、加載指定路徑的XML doc.Load(filePath); //3、獲得根節點 XmlElement root = doc.DocumentElement; //4-1、獲得根節點的所有子節點 //XmlNodeList allNodes = root.ChildNodes; //foreach (XmlNode node in allNodes) //{ // Console.WriteLine(node.InnerText); //} //4-2、獲得某一級別的節點集合 //XmlNodeList booksList = doc.SelectNodes("/Books/Book"); //foreach (XmlNode node in booksList) //{ // Console.WriteLine(node.InnerText); //} //4-3、通過屬性值獲得單個指定的節點,并改變某個屬性的值 XmlNodeList cols = doc.SelectNodes("Config/Table/Column"); //Console.WriteLine(baiYeXing.InnerText); //Console.WriteLine(baiYeXing.Attributes["Count"].Value); //baiYeXing.Attributes["Count"].Value = "9"; //Console.WriteLine(baiYeXing.Attributes["Count"].Value); foreach (XmlNode item in cols) { if (item.Attributes["HeaderText"] != null) { string HeaderText = item.Attributes["HeaderText"].Value; XmlAttribute FlagName = doc.CreateAttribute("FlagName"); FlagName.Value = HeaderText; item.Attributes.Append(FlagName); } } doc.Save(filePath); } } }
https://share.weiyun.com/898239fbc0e5d4358b4de56c1ab8265d
文章列表
全站熱搜