标签:rgs 上下 andself desc from value stat each 基本语法
static void Main(string[] args) { //构造Xml的方法 XElement xlement = new XElement("Customer"); xlement.SetAttributeValue("id", "123"); XElement FirstName = new XElement("Firstname","Joe"); XElement SecondName = new XElement("SecondName", "Blogger"); SecondName.Add(new XComment("nice name")); xlement.Add(FirstName); xlement.Add(SecondName); Console.WriteLine(xlement.ToString()); //与上面代码不一样 但是都是构造xml的代码 var d = new XElement("bench", new XElement("toolbox", new XElement("handtool", "hammer"), new XElement("handtool", "rasp")), new XElement("toolbox", new XElement("handtool", "saw"), new XElement("powertool", "Nail gun"))); Console.WriteLine(d); foreach (var item2 in d.Elements()) { foreach (var item in item2.Elements()) { Console.WriteLine(item.Value+" "); } } //上下两个编码方式不同 但是结果是一样 都是嵌套循环 上面为普通 ,下面为linq to xml //把d.Elements()的值赋值到了x中 然后再使用f来查询 x找出Xlement中Name为handtool的 可以查找出3个 var fff = from x in d.Elements() from t in x.Elements() where t.Name == "handtool" select t.Value; //递归 查d子节含有 handtool 不包含自己 要包含自己则使用 DescendantsAndSelf var dff = d.Descendants("handtool"); foreach (var item in dff) { Console.WriteLine(item.ToString()); } //d.DescendantNodes 与d.Descendants的区别 DescendantNodes查询出的是 子级显示一次 再子级显示一次 并且是无参方法 //eg. var descendantNodes = d.DescendantNodes(); //显示出来就知道区别 foreach (var item in descendantNodes) { Console.WriteLine(item.ToString()); } XElement settings = new XElement("settings", new XElement("timesout", new XElement("timesout2","d"))); // settings.Add(new XElement("timeout", new XElement("timesout2", "ff"))); 1 //settings.SetElementValue("timesout", new XElement("timesout2", "ff")); 2 //1 2 含义相同 //settings.SetElementValue("time1sout", "60"); //精确查找 在xelment中赋值 settings.Descendants("timesout").Elements("timesout2").First().AddAfterSelf(new XElement("d","2")); //把XElment timesout2删除 settings.Descendants("timesout").Elements("timesout2").Remove(); //把 settings.Descendants("timesout").Elements("d").First().ReplaceWith(new XElement("replace", "hehe")); //var dffs2 = from fff1 in settings.Descendants("timesout").Elements() // where fff1.Name == "timesout2" // select fff1; //foreach (var item in dffs2) //{ // item.AddAfterSelf("affter", "d3"); //} Console.WriteLine(settings.ToString()); Console.ReadKey();
标签:rgs 上下 andself desc from value stat each 基本语法
原文地址:http://www.cnblogs.com/yangshasha/p/7807787.html