1. 创建XML文档
static void Main(string[] args) { CreateMusicLibrary(); } static void CreateMusicLibrary() { XDocument musicLibrary = new XDocument( new XDeclaration("1.0","utf-8","yes"),//new XProcessingInstruction("xml-stylesheet","href='music.xslt'"),new XComment("This document holds details of my music collection"),new XElement("musicLibrary",CreateCDElement("1","Parallel Lines",2001,"Blondie","New Wave"),CreateCDElement("2","Bat Out of Hell","Meatloaf","Rock"),CreateCDElement("3","Abbey Road",1987,"The Beatles",CreateCDElement("4","The Dark Side of the Moon",1994,"Pink Floyd",CreateCDElement("5","Thriller","Michael Jackson","Pop"))); Console.WriteLine(musicLibrary.ToString()); //使用ToString方法显示XML文档时会忽略文档中的声明 Console.ReadLine(); } static XElement CreateCDElement(string id,string title,int year,string artist,string genre) { return new XElement("cd",new XAttribute("id",id),new XElement("title",title),new XElement("year",year),new XElement("artist",artist),new XElement("genre",genre)); }
1.1 创建带名称空间的文档,并把名称空间声明为默认名称空间:
static void CreateMusicLibrary() { XNamespace ns = "http://www.wrox.com/namespaces/apps/musicLibrary"; //使用XNamespace类声明命名空间,并将其应用到元素和属性上 XElement musicLibrary = new XElement(ns + "musicLibrary",CreateCDElement(ns,"1","2","3","4","5","Pop")); Console.WriteLine(musicLibrary.ToString()); Console.ReadLine(); } static XElement CreateCDElement(XNamespace ns,string id,string genre) { return new XElement(ns + "cd",new XElement(ns + "title",new XElement(ns + "year",new XElement(ns + "artist",new XElement(ns + "genre",genre)); }
1.2 创建带有前缀名的名称空间文档
static void Main(string[] args) { CreateMusicLibrary(); } static void CreateMusicLibrary() { XNamespace ns = "http://www.wrox.com/namespaces/apps/musicLibrary"; XElement musicLibrary = new XElement(ns + "musicLibrary",new XAttribute(XNamespace.Xmlns + "ns",ns.NamespaceName),//使用XAttribute类将命名空间URI映射到前缀名上 CreateCDElement(ns,genre)); }
2. 从XML 文档中提取数据
需要查询的xml文档如下:
<?xml version="1.0" encoding="utf-8"?> <musicLibrary> <cd id="1"> <title>Parallel Lines</title> <year>2001</year> <artist>Blondie</artist> <genre>New Wave</genre> </cd> <cd id="2"> <title>Bat Out of Hell</title> <year>2001</year> <artist>Meatloaf</artist> <genre>Rock</genre> </cd> <cd id="3"> <title>Abbey Road</title> <year>1987</year> <artist>The Beatles</artist> <genre>Rock</genre> </cd> <cd id="4"> <title>The Dark Side of the Moon</title> <year>1994</year> <artist>Pink Floyd</artist> <genre>Rock</genre> </cd> <cd id="5"> <title>Thriller</title> <year>2001</year> <artist>Michael Jackson</artist> <genre>Pop</genre> </cd> </musicLibrary>要使用LINQ to XML,需要引用System.Xml.Linq程序集
static void Main(string[] args) { XElement musicLibrary = XElement.Load(@"MusicLibrary.xml"); Console.WriteLine("All Titles\n=========="); ShowTitles(musicLibrary); Console.WriteLine("\nTitles before CD 3\n=================="); ShowTitlesBefore(musicLibrary); Console.WriteLine("\nTitles after CD 3\n================="); ShowTitlesAfter(musicLibrary); Console.WriteLine("\nTitles by Genre\n==============="); GroupOnGenre(musicLibrary); Console.ReadLine(); } static void ShowTitles(XElement musicLibrary) { foreach (XElement t in musicLibrary.Elements("cd").Elements("title")) // alternative using Descendants method. // foreach (XElement t in musicLibrary.Descendants("title")) { Console.WriteLine(t.Value); } } static void ShowTitlesBefore(XElement musicLibrary) { XElement cd3 = (from cd in musicLibrary.Elements("cd") where cd.Attribute("id").Value == "3" select cd).FirstOrDefault(); foreach (XElement t in cd3.ElementsBeforeSelf("cd").Elements("title")) { Console.WriteLine(t.Value); } } static void ShowTitlesAfter(XElement musicLibrary) { XElement cd3 = musicLibrary.Elements("cd").Where(cd => cd.Attribute("id").Value == "3").FirstOrDefault(); foreach (XElement t in cd3.ElementsAfterSelf("cd").Elements("title")) { Console.WriteLine(t.Value); } } static void GroupOnGenre(XElement musicLibrary) { var groupQuery = from cd in musicLibrary.Elements("cd") group cd by cd.Element("genre").Value into genreGroup orderby genreGroup.Key select new { Genre = genreGroup.Key,Titles = from title in genreGroup.Elements("title") select title.Value }; foreach (var entry in groupQuery) { Console.WriteLine("Genre: {0}",entry.Genre); Console.WriteLine("----------------"); foreach (var title in entry.Titles) { Console.WriteLine("\t{0}",title); } Console.WriteLine(); } }运行结果如下:
3. 修改XML文档
static void Main(string[] args) { XElement musicLibrary = XElement.Load(@"MusicLibrary.xml"); Console.WriteLine("Adding a New CD\n==============="); AddNewCD(musicLibrary); Console.WriteLine(musicLibrary); Console.WriteLine("\nRemoving a CD============="); RemoveCD(musicLibrary); Console.WriteLine(musicLibrary); Console.WriteLine("\nAdding a New CD Directly\n========================"); AddNewCDDirectly(musicLibrary); Console.WriteLine(musicLibrary); Console.WriteLine("\nUpdate Year with ReplaceNodes\n============================="); UpdateYearWithReplaceNodes(musicLibrary); Console.WriteLine(musicLibrary); Console.WriteLine("\nUpdate Year with SetElementValue================================"); UpdateYearWithSetElementValue(musicLibrary); Console.WriteLine(musicLibrary); Console.WriteLine("\nUpdate Attribute Value===================="); UpdateAttributeValue(musicLibrary); Console.WriteLine(musicLibrary); Console.WriteLine("\nReplace CD Content=================="); ReplaceCD(musicLibrary); Console.WriteLine(musicLibrary); Console.ReadLine(); } static void AddNewCD(XElement musicLibrary) { XElement cd = CreateCDElement("6","Back in Black",2003,"AC/DC","Rock"); musicLibrary.Add(cd); } static void AddNewCDDirectly(XElement musicLibrary) { musicLibrary.Add( new XElement("cd",6),"Back in Black"),2003),"AC/DC"),"Rock"))); } static void RemoveCD(XElement musicLibrary) { XElement cd = (from entry in musicLibrary.Elements("cd") where entry.Attribute("id").Value == "6" select entry).FirstOrDefault(); if (null != cd) { cd.Remove(); } } static XElement CreateCDElement(string id,genre)); } static void UpdateYearWithReplaceNodes(XElement musicLibrary) { XElement cd = (from entry in musicLibrary.Elements("cd") where entry.Attribute("id").Value == "3" select entry).FirstOrDefault(); cd.Element("year").ReplaceNodes("1986"); } static void UpdateYearWithSetElementValue(XElement musicLibrary) { XElement cd = (from entry in musicLibrary.Elements("cd") where entry.Attribute("id").Value == "3" select entry).FirstOrDefault(); cd.SetElementValue("year","1987"); } static void UpdateAttributeValue(XElement musicLibrary) { XElement cd = (from entry in musicLibrary.Elements("cd") where entry.Attribute("id").Value == "3" select entry).FirstOrDefault(); cd.SetAttributeValue("id","7"); } static void ReplaceCD(XElement musicLibrary) { XElement cd = (from entry in musicLibrary.Elements("cd") where entry.Attribute("id").Value == "1" select entry).FirstOrDefault(); cd.ReplaceWith( new XElement("cd",1),"Rock"))); }原文链接:https://www.f2er.com/xml/299009.html