您的位置:首页 > 其它

LINQ TO XML 基本操作

2010-12-25 21:15 477 查看
[code] 6.1test.xml
<?xml version="1.0" encoding="utf-8"?>
<TabAddressBookEntity xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/DemoOrder">
<Address i:nil="true" />
<Age>19</Age>
<Company i:nil="true" />
<Duty>乖巧人儿</Duty>
<MainID>4</MainID>
<Name>董巧巧</Name>
<Sex>女</Sex>
<TabShoppingListEntity>
<TabShoppingListEntity>
<AddressBookID>4</AddressBookID>
<Amount>1</Amount>
<Date i:nil="true" />
<ID>9</ID>
<Price>60000.0000</Price>
<Product>1克拉钻石戒指</Product>
<Unit>个</Unit>
</TabShoppingListEntity>
<TabShoppingListEntity>
<AddressBookID>4</AddressBookID>
<Amount>1</Amount>
<Date i:nil="true" />
<ID>10</ID>
<Price>1000000.0000</Price>
<Product>旺角酒楼</Product>
<Unit>座</Unit>
</TabShoppingListEntity>
</TabShoppingListEntity>
<TelphoneNumber>029*-981256**</TelphoneNumber>
</TabAddressBookEntity>
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
////// <summary>
///查询 test.xml
/// </summary>
namespace DemoLinqToXml
{
 class Program
{
 static void Main(string[] args)
{
 XDocument xdoc = null;
 using (StreamReader sr = new StreamReader("test.xml"))
{
 //从文件中载入XML
 xdoc = XDocument.Parse(sr.ReadToEnd());
}
 //使用LINQ表达式查找Product节点,获取节点的值
 IEnumerable<string> products = from ele in xdoc.Descendants()
where ele.Name.LocalName == "Product"
select ele.Value;
 foreach (string p in products)
 Console.WriteLine(p);
 Console.ReadKey();
}
}
}
///<summary>
 ///从Internet 装载XML文档构建XDocument
/// </summary>
using System;
using System.Xml.Linq;
namespace DemoXDocument
{
 class Program
{
 static void Main(string[] args)
{
 //从URI加载 XML 文档生成 XDocument 对象
 XDocument doc = XDocument.Load("http://rss.sina.com.cn/news/marquee/ddt.xml");
 //为了方便查看,省略一些子节点
 doc.Descendants("item").Remove();
 //为了方便查看,省略注释的一些内容
 foreach (var n in doc.Nodes())
{
 XComment comm = n as XComment;
 if (comm != null)
 comm.Value = string.Format("{0} ...... ",comm.Value.Substring(0, 30));
}
 
 Console.WriteLine(doc);
 Console.ReadKey();
}
}
}
////// <summary>
///
/// 给XDocument 对象增加元素
///
/// </summary>
using System;
using System.Xml.Linq;
namespace DemoXAttribute1
{
 class Program
{
 static void Main(string[] args)
{
 XElement root = new XElement("根元素",
 new XAttribute("属性1", "值"),
 new XAttribute("属性2", "0"));
 XElement child = new XElement("子元素1");
 child.Add(new XAttribute("子节点上的属性", "**"));
 XDocument doc = new XDocument(root);
 doc.Root.Add(child,
 new XElement("子元素2", "元素值"),
 new XElement("子元素3")
 );
 Console.WriteLine(doc);
 Console.ReadKey();
}
}
}
////// <summary>
///XComment("这是根节点的注释内容")
/// </summary>
using System;
using System.Xml.Linq;
namespace DemoXComment
{
 class Program
{
 static void Main(string[] args)
{
 XElement root = new XElement("根元素",
 new XComment("这是根节点的注释内容"),
 new XAttribute("属性", "0"));
 XDocument doc = new XDocument(new XComment("这是文档的注释内容"),root);
 doc.Root.Add(new XElement("子元素", "元素值"),
 new XElement("子元素")
 );
 Console.WriteLine(doc);
 Console.ReadKey();
}
}
}
////// <summary>
///使用XDeclaration 给XDocument对象增加声明
/// </summary>
using System;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Text;
namespace DemoXDeclaration
{
 class Program
{
 static void Main(string[] args)
{
 XElement root = new XElement("根元素",
 new XAttribute("属性", "0"));
 XDocument doc = new XDocument(new XComment("这是文档的注释内容"), root);
 doc.Declaration = new XDeclaration("1.0", "utf-16", "yes");
 doc.Root.Add(new XElement("子元素"),
 new XElement("子元素")
 );
 StringWriter sw = new StringWriter();
 doc.Save(sw, SaveOptions.None);
 sw.Close();
 Console.WriteLine(sw.ToString());
 Console.ReadKey();
}
}
}
////// <summary>
///XDocumentType 表示文档类型
/// </summary>
using System;
using System.Xml.Linq;
namespace DemoXDocumentType
{
 class Program
{
 static void Main(string[] args)
{
 XElement root = new XElement("根元素",
new XAttribute("属性", "0"));
 XDocument doc = new XDocument(
 new XDocumentType("限定名","Test Name","专用标识符","内部子集"),
 new XComment("这是文档的注释内容"), root);
 doc.Root.Add(new XElement("子元素"),
 new XElement("子元素")
 );
 Console.WriteLine(doc);
 Console.ReadKey();
}
}
}
////// <summary>
///XProcessingInstruction表示XML出来命令
/// </summary>
using System;
using System.Xml.Linq;
namespace DemoXProcessingInstruction
{
 class Program
{
 static void Main(string[] args)
{
 XElement root = new XElement("根元素",
new XAttribute("属性", "0"));
 XDocument doc = new XDocument(
 new XProcessingInstruction ("xml-stylesheet", "type='text/xsl' href='test.xsl'"),
 new XDocumentType("限定名", "Test Name", "专用标识符", "内部子集"),
 new XComment("这是文档的注释内容"), root);
 doc.Root.Add(new XElement("子元素"),
 new XElement("子元素")
 );
 Console.WriteLine(doc);
 Console.ReadKey();
}
}
}
////// <summary>
///XCData 表示一个文本节点
/// </summary>
using System;
using System.Xml.Linq;
namespace DemoXCdata
{
 class Program
{
 static void Main(string[] args)
{
 XElement root = new XElement("根元素",
new XAttribute("属性", "0")
);
 XDocument doc = new XDocument(
 new XProcessingInstruction("xml-stylesheet", "type='text/xsl' href='test.xsl'"),
 new XDocumentType("限定名", "Test Name", "专用标识符", "内部子集"),
 new XComment("这是文档的注释内容"), root);
 root.Add(new XElement("子元素"),
 
 new XElement("子元素")
 );
 root.Add(new XCData("这里是根元素的CDATA节点"));
 Console.WriteLine(doc);
 Console.ReadKey();
}
}
}
////// <summary>
 ///XNamespace sp = "http://www.tiyor.com";命名空间
/// </summary>
using System;
using System.Xml.Linq;
namespace DemoXNamespace
{
 class Program
{
 static void Main(string[] args)
{
 XNamespace sp = "http://www.tiyor.com";
 XElement root = new XElement(sp + "根元素",
 new XAttribute("属性", "0")
 );
 XDocument doc = new XDocument(
 new XProcessingInstruction("xml-stylesheet", "type='text/xsl' href='test.xsl'"),
 new XDocumentType("限定名", "Test Name", "专用标识符", "内部子集"),
 new XComment("这是文档的注释内容"), root);
 root.Add(new XElement(sp + "子元素"),
 new XElement(sp + "子元素")
 );
 root.Add(new XCData("这里是根元素的CDATA节点"));
 Console.WriteLine(doc);
 Console.ReadKey();
}
}
}
////// <summary>
 ///构建XEelement
 ///
/// </summary>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
namespace DemoXElement
{
 class Program
{
 static void Main(string[] args)
{
 //使用原型一构建
 XElement el1 = new XElement("原型1根节点");
 Console.WriteLine(el1);
 Console.WriteLine("***********************************");
 //使用原型2构建
 XElement el2 = new XElement(el1);
 el2.Name = "原型2根节点";
 Console.WriteLine(el2);
 Console.WriteLine("***********************************");
 //使用原型3构建
 XElement el3 = new XElement(
 new XStreamingElement("原型3根节点",
 from el in el1.Elements()
 select el
 )
 );
 Console.WriteLine(el3);
 Console.WriteLine("***********************************");
 //使用原型4构建
 XElement el4 = new XElement("原型4根节点",new XElement("原型4的子节点"));
 Console.WriteLine(el4);
 Console.WriteLine("***********************************");
 //使用原型5构建
 XElement el5 = new XElement("原型5根节点", 
 new XElement("原型5的子节点",1),
 new XElement("原型5的子节点",2),
 new XElement("原型5的子节点",3)
 );
 Console.WriteLine(el5);
 Console.ReadKey();
}
}
}
////// <summary>
///Parse 方法 与使用Element 检索元素的轴方法
/// </summary>
using System;
using System.Xml.Linq;
namespace DemoXElementMethod
{
 class Program
{
 static void Main(string[] args)
{
 string sxml = @"<根节点>
 <子节点>1</子节点>
 <子节点>2</子节点>
 <子节点>3</子节点>
 <子节点>4</子节点>
 <子节点>5</子节点>
 <子节点>6</子节点>
</根节点>";
 XElement el = XElement.Parse(sxml);
 XElement elChild = el.Element("子节点");
 Console.WriteLine(elChild);
 Console.ReadKey();
}
}
}
////// <summary>
///Elements\Descendants 方法检索子元素集合
/// </summary>
using System;
using System.Collections.Generic;
using System.Xml.Linq;
namespace DemoXElements
{
 class Program
{
 static void Main(string[] args)
{
 string sxml = @"<根节点>
 <子节点>
 <第3级>1</第3级>
 <第3级>2</第3级>
</子节点>
 <子节点>2</子节点>
 <子节点>3</子节点>
 <子节点>4</子节点>
 <子节点>5</子节点>
 <子节点>6</子节点>
</根节点>";
 XElement el = XElement.Parse(sxml);
 Console.WriteLine("应用Elements方法返回的子元素集合");
 IEnumerable<XElement> elChilds = el.Elements();
 foreach (XElement e in elChilds)
 Console.WriteLine(e.Name.LocalName);
 Console.WriteLine("\n应用Descendants方法返回的子元素集合");
 IEnumerable<XElement> elChilds2 = el.Descendants();
 foreach (XElement e in elChilds2)
 Console.WriteLine(e.Name.LocalName);
 Console.ReadKey();
}
}
}
////// <summary>
///Ancestors\ AncestorsAndSelf 方法检索父级元素
/// </summary>
using System;
using System.Linq;
using System.Xml.Linq;
namespace DemoXAncestors
{
 class Program
{
 static void Main(string[] args)
{
 string sxml = @"<根节点>
 <子节点1>
 <第3级节点 />
 </子节点1>
 <子节点2 />
 <子节点3 />
 <子节点4 />
</根节点>";
 XElement el = XElement.Parse(sxml);
 XElement el2 = el.Descendants("第3级节点").First();
 Console.WriteLine("应用Ancestors方法返回父元素集合");
 foreach(XElement e in el2.Ancestors())
 Console.WriteLine(e.Name.LocalName);
 Console.WriteLine("\n应用AncestorsAndSelf方法返回父元素集合");
 foreach (XElement e in el2.AncestorsAndSelf())
 Console.WriteLine(e.Name.LocalName);
 Console.ReadKey();
}
}
}
////// <summary>
///应用ElementsAfterSelf方法返回该元素之后同级的元素集合
///应用ElementsBeforeSelf方法返回该元素之前同级的元素集合
/// </summary>
using System;
using System.Collections.Generic;
using System.Xml.Linq;
namespace DemoXElementsMethod
{
 class Program
{
 static void Main(string[] args)
{
 string sxml = @"<根节点>
 <子节点1 /> 
 <子节点2 />
 <Test子节点 />
 <子节点4 />
 <子节点5 />
 <子节点6 />
</根节点>";
 XElement el = XElement.Parse(sxml);
 IEnumerable<XElement> els = el.Element("Test子节点").ElementsAfterSelf();
 Console.WriteLine("应用ElementsAfterSelf方法返回的元素集合");
 foreach (XElement e in els)
 Console.WriteLine(e);
 IEnumerable<XElement> els2 = el.Element("Test子节点").ElementsBeforeSelf();
 Console.WriteLine("应用ElementsBeforeSelf方法返回的元素集合");
 foreach (XElement e in els2)
 Console.WriteLine(e);
 Console.ReadKey();
}
}
}
////// <summary>
///XValue 
/// </summary>
using System;
using System.Xml.Linq;
namespace DemoXValue
{
 class Program
{
 static void Main(string[] args)
{
 string sxml = @"<根节点>
 <子节点>1</子节点>
 <子节点>
 <第3级>1</第3级>
 <第3级>2</第3级>
 </子节点>
 <子节点2>2</子节点2>
 <子节点3>字符串值</子节点3>
 <子节点>4</子节点>
</根节点>";
 XElement el = XElement.Parse(sxml);
 Console.WriteLine("第一个子节点的值:{0}", el.Element("子节点").Value);
 string svalue = (string)el.Element("子节点3");
 Console.WriteLine("强制转换得到子节点3的值:{0}", svalue);
 int? ivalue = (int?)el.Element("不存在的节点");
 Console.WriteLine("可空类型的强制转换:{0}", ivalue == null ? "值为null" : ivalue.ToString());
 int ivalue2 = (int)el.Element("子节点2");
 Console.WriteLine("强制转换得到子节点2的值:{0}", ivalue2);
 el.Element("子节点2").Value = "字符串值";
 Console.WriteLine("子节点2的Value:{0}", el.Element("子节点2").Value);
 el.Element("子节点2").SetValue(12345);
 Console.WriteLine("子节点2的Value:{0}", el.Element("子节点2").Value);
 Console.ReadKey();
}
}
}
////// <summary>
///Add\AddAfterSelf\AddBeforeSelf\AddFirst
/// </summary>
using System;
using System.Xml.Linq;
namespace DemoXAdd
{
 class Program
{
 static void Main(string[] args)
{
 XElement el = new XElement("根节点");
 el.Add(new XElement("Add添加的子节点"));
 el.Add(new XElement("Add添加的子节点"),
 new XElement("Add添加的子节点")
 );
 el.AddFirst(new XElement("AddFirst添加的子节点"));
 el.Element("AddFirst添加的子节点").AddAfterSelf(new XElement("AddAfterSelf添加的节点"));
 el.Element("AddFirst添加的子节点").AddBeforeSelf(new XElement("AddBeforeSelf添加的节点"));
 Console.WriteLine(el);
 Console.ReadKey();
}
}
}
运行结果:
<根节点>
 <AddBeforeSelf添加的节点 />
 <AddFirst添加的子节点 />
 <AddAfterSelf添加的节点 />
 <Add添加的子节点 />
 <Add添加的子节点 />
 <Add添加的子节点 />
</根节点>
////// <summary>
///Remove\RemoveAll 删除元素
/// </summary>
using System;
using System.Xml.Linq;
namespace DemoXRemove
{
 class Program
{
 static void Main(string[] args)
{
 XElement el = new XElement("根节点");
 el.Add(new XElement("子节点1"),
 new XElement("子节点2"),
 new XElement("子节点3"),
 new XElement("子节点4")
 );
 el.Element("子节点3").Remove();
 Console.WriteLine(el);
 el.RemoveAll();
 Console.WriteLine("\n对根节点应用RemoveAll方法后");
 Console.WriteLine(el);
 Console.ReadKey();
}
}
}
////// <summary>
///ReplaceWith替换元素
/// </summary>
using System;
using System.Xml.Linq;
namespace DemoXReplaceWith
{
 class Program
{
 static void Main(string[] args)
{
 string sxml = @"<根节点>
 <子节点1 />
 <子节点2 />
 <子节点3 />
 <子节点4 />
</根节点>";
 XElement el = XElement.Parse(sxml);
 el.Element("子节点2").ReplaceWith(new XElement("原型一替换的"));
 Console.WriteLine("应用ReplaceWith原型一之后");
 Console.WriteLine(el);
 el.Element("子节点3").ReplaceWith(new XElement("替换3"), new XElement("新加入"));
 Console.WriteLine("\n应用ReplaceWith原型二之后");
 Console.WriteLine(el);
 Console.ReadKey();
}
}
}
////// <summary>
///ReplaceAll方法替换元素的子节点
/// </summary>
using System;
using System.Xml.Linq;
namespace DemoXReplaceAll
{
 class Program
{
 static void Main(string[] args)
{
 string sxml = @"<根节点>
 <子节点1 />
 <子节点2 />
 <子节点3 />
 <子节点4 />
</根节点>";
 XElement el = XElement.Parse(sxml);
 el.Element("子节点2").ReplaceAll(new XElement("ReplaceAll原型一"));
 Console.WriteLine("应用ReplaceAll原型一之后");
 Console.WriteLine(el);
 el.Element("子节点3").ReplaceAll(new XElement("ReplaceAll原型二"), new XElement("ReplaceAll原型二"));
 Console.WriteLine("\n应用ReplaceAll原型二之后");
 Console.WriteLine(el);
 Console.ReadKey();
}
}
}
////// <summary>
///SetElementValue
/// </summary>
using System;
using System.Xml.Linq;
namespace DemoXSetElementValue
{
 class Program
{
 static void Main(string[] args)
{
 string sxml = @"<根节点>
 <子节点1>
<第3级 />
</子节点1>
 <子节点2 />
 <子节点3 />
 <子节点4 />
</根节点>";
 XElement el = XElement.Parse(sxml);
 //移除第3级子元素
 el.Element("子节点1").SetElementValue("第3级", null);
 //新添加子元素
 el.Element("子节点1").SetElementValue("新添加子元素", "测试值");
 Console.WriteLine(el.Element("子节点1"));
 //修改新添加子元素
 el.Element("子节点1").SetElementValue("新添加子元素", "修改值");
 Console.WriteLine(el.Element("子节点1"));
 Console.ReadKey();
}
}
}
////// <summary>
///Attributes 获取元素的属性集合
/// </summary>
using System;
using System.Xml.Linq;
namespace DemoXAttributes
{
 class Program
{
 static void Main(string[] args)
{
 string sxml = @"<根节点>
 <子节点1 属性1='1' 属性2='测试' />
 <子节点2 />
 <子节点3 />
 <子节点4 />
</根节点>";
 XElement el = XElement.Parse(sxml);
 foreach( var a in el.Element("子节点1").Attributes())
 Console.WriteLine(a);
 Console.ReadKey();
}
}
}
using System;
using System.Xml.Linq;
namespace DemoXAttribute
{
 class Program
{
 static void Main(string[] args)
{
 string sxml = @"<根节点>
 <子节点1 属性1='1' 属性2='测试' />
 <子节点2 />
 <子节点3 />
 <子节点4 />
</根节点>";
 XElement el = XElement.Parse(sxml);
 Console.WriteLine(el.Element("子节点1").Attribute("属性2"));
 Console.WriteLine(el.Element("子节点1").Attribute("属性3") == null ? "属性3并不存在" : el.Element("子节点1").Attribute("属性3").ToString());
 Console.ReadKey();
}
}
}
////// <summary>
///ReplaceAttributes 方法替换属性
/// </summary>
using System;
using System.Xml.Linq;
namespace DemoXReplaceAttributes
{
 class Program
{
 static void Main(string[] args)
{
 string sxml = @"<根节点>
 <子节点1 属性1='测试'/>
 <子节点2 />
 <子节点3 />
 <子节点4 />
</根节点>";
 XElement el = XElement.Parse(sxml);
 el.Element("子节点1").ReplaceAttributes(new XAttribute("原型一替换",0));
 Console.WriteLine("应用ReplaceAttributes原型一之后");
 Console.WriteLine(el.Element("子节点1"));
 el.Element("子节点1").ReplaceAttributes(new XAttribute("原型二替换",0), new XAttribute("原型二添加",0));
 Console.WriteLine("\n应用ReplaceAttributes原型二之后");
 Console.WriteLine(el.Element("子节点1"));
 Console.ReadKey();
}
}
}
using System;
using System.Xml.Linq;
namespace DemoXRemoveAttributes
{
 class Program
{
 static void Main(string[] args)
{
 string sxml = @"<根节点>
 <子节点1 属性1='测试' 属性2='0'>
<第3级 属性='1'/>
</子节点1>
 <子节点2 />
</根节点>";
 XElement el = XElement.Parse(sxml);
 Console.WriteLine("应用RemoveAttributes之后");
 el.Element("子节点1").RemoveAttributes();
 Console.WriteLine(el);
 el.Element("子节点1").RemoveAll();
 Console.WriteLine("\n应用RemoveAll之后");
 Console.WriteLine(el);
 Console.ReadKey();
}
}
}
using System;
using System.Xml.Linq;
namespace DemoXSetAttributeValue
{
 class Program
{
 static void Main(string[] args)
{
 string sxml = @"<根节点>
 <子节点1 属性1='测试'/>
 <子节点2 />
 <子节点3 />
 <子节点4 />
</根节点>";
 XElement el = XElement.Parse(sxml);
 //移除属性1
 el.Element("子节点1").SetAttributeValue("属性1", null);
 //添加属性Test
 el.Element("子节点1").SetAttributeValue("属性Test", "测试值");
 Console.WriteLine(el.Element("子节点1"));
 //修改属性Test
 el.Element("子节点1").SetAttributeValue("属性Test", "修改值");
 Console.WriteLine(el.Element("子节点1"));
 Console.ReadKey();
}
}
}
using System;
using System.Xml.Linq;
namespace DemoXAnnotations
{
 class Program
{
 static void Main(string[] args)
{
 string sxml = @"<根节点>
 <子节点1 />
 <子节点2 />
 <子节点3 />
 <子节点4 />
</根节点>";
 XElement el = XElement.Parse(sxml);
 el.Element("子节点1").AddAnnotation("批注1");
 el.Element("子节点1").AddAnnotation("批注2");
 el.Element("子节点1").AddAnnotation("批注3");
 Console.WriteLine("子节点1的批注对象");
 //访问批注对象集合
 foreach (string s in el.Element("子节点1").Annotations<string>())
 Console.WriteLine(s);
 Console.ReadKey();
}
}
}
using System;
using System.Linq;
using System.Text;
using System.Xml.Linq;
namespace DemoXRemoveAnnotations
{
 class Program
{
 static void Main(string[] args)
{
 string sxml = @"<根节点>
 <子节点1>
 <第3级 />
 </子节点1>
 <子节点2 />
 <子节点3 />
 <子节点4 />
</根节点>";
 XElement el = XElement.Parse(sxml);
 el.Element("子节点1").AddAnnotation("批注1");
 el.Element("子节点1").AddAnnotation("批注2");
 el.Element("子节点1").AddAnnotation("批注3");
 el.Element("子节点1").AddAnnotation(new StringBuilder());
 el.Element("子节点1").AddAnnotation(new StringBuilder());
 
 el.Element("子节点1").Element("第3级").AddAnnotation("第3级批注");
 el.Element("子节点1").RemoveAnnotations<string>();
 Console.WriteLine("子节点1的string批注对象数:{0}", el.Element("子节点1").Annotations<string>().Count());
 Console.WriteLine("子节点1的StringBuilder批注对象数:{0}", el.Element("子节点1").Annotations<StringBuilder>().Count());
 Console.WriteLine("第3级的string批注对象数:{0}", el.Element("子节点1").Element("第3级").Annotations<string>().Count());
 Console.ReadKey();
}
}
}
///summary
///查询
///summary
using System;
using System.Linq;
using System.Xml.Linq;
namespace DemoXQuery1
{
 class Program
{
 static void Main(string[] args)
{
 string sxml = @"<通讯录>
 <客户 姓名='肖青漩' 年龄='21'>
<职务>出云公主</职务>
<电话>017*-876543**</电话>
 </客户>
 <客户 姓名='董巧巧' 年龄='19'>
<职务>乖巧人儿</职务>
<电话>029*-981256**</电话>
 </客户>
 <客户 姓名='萧玉霜' 年龄='17'>
<职务>萧家二小姐</职务>
<电话>053*-985690**</电话>
 </客户>
 </通讯录>";
 XElement root = XElement.Parse(sxml);
 //筛选年龄属性大于18的客户
 var query = from item in root.Elements("客户")
 where (from att in item.Attributes()
where att.Name.LocalName == "年龄"
select att).Any(age=>(int)age>18)
 select item;
 foreach (var el in query)
 Console.WriteLine(el);
 Console.ReadKey();
 
}
}
}
////// <summary>
///Order 对XML元素进行排序
/// </summary>
using System;
using System.Linq;
using System.Xml.Linq;
namespace DemoXOrder
{
 class Program
{
 static void Main(string[] args)
{
 string sxml = @"<通讯录>
 <客户 姓名='肖青漩' 年龄='21'>
<职务>出云公主</职务>
<电话>017*-876543**</电话>
 </客户>
 <客户 姓名='董巧巧' 年龄='19'>
<职务>乖巧人儿</职务>
<电话>029*-981256**</电话>
 </客户>
 <客户 姓名='萧玉霜' 年龄='17'>
<职务>萧家二小姐</职务>
<电话>053*-985690**</电话>
 </客户>
 <客户 姓名='秦仙儿' 年龄='20'>
<职务>霓裳公主</职务>
<电话>023*-338987**</电话>
 </客户>
 <客户 姓名='萧玉若' 年龄='21'>
<职务>萧家大小姐</职务>
<电话>035*-120967**</电话>
 </客户>
 <客户 姓名='洛凝' 年龄='19'>
<职务>金陵才女</职务>
<电话>033*-985690**</电话>
 </客户>
 </通讯录>";
 XElement root = XElement.Parse(sxml);
 var query = from item in root.Elements("客户")
 orderby (int)item.Attribute("年龄"), item.Element("电话").Value
 select item;
 foreach (var el in query)
 Console.WriteLine(el);
 Console.ReadKey();
}
}
}
////// <summary>
///对XMLelment 元素进行计算
/// </summary>
using System;
using System.Linq;
using System.Xml.Linq;
namespace DemoXCount
{
 class Program
{
 static void Main(string[] args)
{
 string sxml = @"<通讯录>
 <客户 姓名='肖青漩' 年龄='21'>
<职务>出云公主</职务>
<电话>017*-876543**</电话>
<订货单>
<品名>6克拉钻石戒指</品名>
<单价>120,000</单价>
<数量>3</数量>
</订货单>
<订货单>
<品名>真丝旗袍</品名>
<单价>3,600</单价>
<数量>2</数量>
</订货单>
 </客户>
 <客户 姓名='董巧巧' 年龄='19'>
<职务>乖巧人儿</职务>
<电话>029*-981256**</电话>
<订货单>
<品名>旺角酒楼</品名>
<单价>2,500,000</单价>
<数量>1</数量>
</订货单>
<订货单>
<品名>奥迪TT</品名>
<单价>650,000</单价>
<数量>1</数量>
</订货单>
 </客户>
 <客户 姓名='萧玉霜' 年龄='17'>
<职务>萧家二小姐</职务>
<电话>053*-985690**</电话>
 </客户>
 <客户 姓名='秦仙儿' 年龄='20'>
<职务>霓裳公主</职务>
<电话>023*-338987**</电话>
<订货单>
<品名>独门四合院</品名>
<单价>12,000,000</单价>
<数量>1</数量>
</订货单>
 </客户>
 <客户 姓名='萧玉若' 年龄='21'>
<职务>萧家大小姐</职务>
<电话>035*-120967**</电话>
 </客户>
 <客户 姓名='洛凝' 年龄='19'>
<职务>金陵才女</职务>
<电话>033*-985690**</电话>
 </客户>
 </通讯录>";
 XElement root = XElement.Parse(sxml);
 var query = from item in root.Elements("客户")
 let cc = (from l in item.Elements("订货单")
 let c = Convert.ToDouble(l.Element("单价").Value) * (double)l.Element("数量")
 select c).Sum()
 orderby cc descending
 select new{ Guest = item, Count = cc};
 foreach (var item in query)
{
 Console.WriteLine("姓名:{0} 订单总价:{1}", item.Guest.Attribute("姓名").Value, item.Count.ToString("C"));
 foreach (var p in item.Guest.Elements("订货单"))
 Console.WriteLine("{0}{1}{2}", p.Element("品名").Value, p.Element("单价").Value, p.Element("数量").Value);
 Console.WriteLine("----------------------------------------------");
}
 Console.ReadKey();
}
}
}
////// <summary>
///剔除XML中符合条件的元素
/// </summary>
using System;
using System.Linq;
using System.Xml.Linq;
namespace DemoLinqRemove
{
 class Program
{
 static void Main(string[] args)
{
 string sxml = @"<通讯录>
 <客户 姓名='肖青漩' 年龄='21'>
<职务>出云公主</职务>
<电话>017*-876543**</电话>
<订货单>
<品名>6克拉钻石戒指</品名>
<单价>120,000</单价>
<数量>3</数量>
</订货单>
<订货单>
<品名>真丝旗袍</品名>
<单价>3,600</单价>
<数量>2</数量>
</订货单>
 </客户>
 <客户 姓名='董巧巧' 年龄='19'>
<职务>乖巧人儿</职务>
<电话>029*-981256**</电话>
<订货单>
<品名>旺角酒楼</品名>
<单价>2,500,000</单价>
<数量>1</数量>
</订货单>
<订货单>
<品名>奥迪TT</品名>
<单价>650,000</单价>
<数量>1</数量>
</订货单>
 </客户>
 <客户 姓名='萧玉霜' 年龄='17'>
<职务>萧家二小姐</职务>
<电话>053*-985690**</电话>
 </客户>
 <客户 姓名='秦仙儿' 年龄='20'>
<职务>霓裳公主</职务>
<电话>023*-338987**</电话>
<订货单>
<品名>独门四合院</品名>
<单价>12,000,000</单价>
<数量>1</数量>
</订货单>
 </客户>
 <客户 姓名='萧玉若' 年龄='21'>
<职务>萧家大小姐</职务>
<电话>035*-120967**</电话>
 </客户>
 <客户 姓名='洛凝' 年龄='19'>
<职务>金陵才女</职务>
<电话>033*-985690**</电话>
 </客户>
 </通讯录>";
 XElement root = XElement.Parse(sxml);
 //剔除订单总价等于0的客户
 (from item in root.Elements("客户")
let cc = (from l in item.Elements("订货单")
let c = Convert.ToDouble(l.Element("单价").Value) * (double)l.Element("数量")
select c).Sum()
where cc == 0
select item).Remove();
 //剔除XML树中的订单
 (from item in root.Elements("客户")
from l in item.Elements("订货单") 
select l).Remove();
 Console.WriteLine(root);
 
 Console.ReadKey();
}
}
}
////// <summary>
 ///变造XML树
/// </summary>
using System;
using System.Linq;
using System.Xml.Linq;
namespace DemoTransforming
{
 class Program
{
 static void Main(string[] args)
{
 string sxml = @"<通讯录>
 <客户 姓名='肖青漩' 年龄='21'>
<职务>出云公主</职务>
<电话>017*-876543**</电话>
<订货单>
<品名>6克拉钻石戒指</品名>
<单价>120,000</单价>
<数量>3</数量>
</订货单>
<订货单>
<品名>真丝旗袍</品名>
<单价>3,600</单价>
<数量>2</数量>
</订货单>
 </客户>
 <客户 姓名='董巧巧' 年龄='19'>
<职务>乖巧人儿</职务>
<电话>029*-981256**</电话>
<订货单>
<品名>旺角酒楼</品名>
<单价>2,500,000</单价>
<数量>1</数量>
</订货单>
<订货单>
<品名>奥迪TT</品名>
<单价>650,000</单价>
<数量>1</数量>
</订货单>
 </客户>
 <客户 姓名='萧玉霜' 年龄='17'>
<职务>萧家二小姐</职务>
<电话>053*-985690**</电话>
 </客户>
 <客户 姓名='秦仙儿' 年龄='20'>
<职务>霓裳公主</职务>
<电话>023*-338987**</电话>
<订货单>
<品名>独门四合院</品名>
<单价>12,000,000</单价>
<数量>1</数量>
</订货单>
 </客户>
 <客户 姓名='萧玉若' 年龄='21'>
<职务>萧家大小姐</职务>
<电话>035*-120967**</电话>
 </客户>
 <客户 姓名='洛凝' 年龄='19'>
<职务>金陵才女</职务>
<电话>033*-985690**</电话>
 </客户>
 </通讯录>";
 XElement root = XElement.Parse(sxml);
 //统计结果
 var count = from item in root.Elements("客户")
 let cc = (from l in item.Elements("订货单") let c = Convert.ToDouble(l.Element("单价").Value) * (double)l.Element("数量") select c).Sum()
 where cc > 0
 select new{ Count = cc, Node = item};
 ///变造新的XML树
 XElement newroot = new XElement
 (
 "客户订单表",
 new XElement("订单总价", count.Sum(item => item.Count).ToString("c")),
 new XElement("订户总数", count.Count()),
 new XElement("明细",
 (from i in count
select new XElement(i.Node.Name, i.Node.Attribute("姓名"),
new XAttribute("电话", i.Node.Element("电话").Value),
new XAttribute("小计", i.Count.ToString("c")),
(from p in i.Node.Elements("订货单") select new XElement("订货", from l in p.Elements() select new XAttribute(l.Name, l.Value)))))
 )
 );
 Console.WriteLine(newroot);
 Console.ReadKey();
}
}
}
using System;
using System.Linq;
using System.Xml.Linq;
namespace DemoTransforming2
{
 class Program
{
 static void Main(string[] args)
{
 string sxml = @"<数据>
 <字>你 赵 月 钱 李 王 孙 喜 晨 曦 我 凡 宝 悦 爱</字>
 <数>2 3 4 5 6 7</数>
 <颜色>粉 绿 黄 兰</颜色>
 <其他>蛋糕 妈妈 衣服</其他>
 </数据>";
 XElement root = XElement.Parse(sxml);
 ///变造新的XML树
 XElement newroot = new XElement
 (
 new XElement("我的宝贝",
 new XElement("姓名",
 string.Format("{0}{1}{2}",
 root.Element("字").Value.Split(' ').ElementAt(5),
 root.Element("字").Value.Split(' ').ElementAt(9),
 root.Element("字").Value.Split(' ').ElementAt(13))),
new XElement("乳名",
string.Format("{0}{1}",
 root.Element("字").Value.Split(' ').ElementAt(2),
 root.Element("字").Value.Split(' ').ElementAt(2))),
new XElement("年龄",
string.Format("{0}岁",
 root.Element("数").Value.Split(' ').ElementAt(1))),
 new XElement("喜欢的颜色",
string.Format("{0}色",
 root.Element("颜色").Value.Split(' ').First())),
new XElement("喜欢的食物",
root.Element("其他").Value.Split(' ').First()),
new XElement("最喜欢的人",
root.Element("其他").Value.Split(' ').ElementAt(1)),
new XElement("经常说的话", 
string.Format("{0}{1}{2}{3}",
root.Element("其他").Value.Split(' ').ElementAt(1),
root.Element("字").Value.Split(' ').ElementAt(10),
root.Element("字").Value.Split(' ').Last(),
root.Element("字").Value.Split(' ').First())),
 new XElement("依恋物", 
string.Format("{0}{1}",
root.Element("其他").Value.Split(' ').ElementAt(1),
root.Element("其他").Value.Split(' ').Last()))
)
);
 Console.WriteLine(newroot);
 Console.ReadKey();
}
}
}
////// <summary>
///利用XML中XDocument重载函数ToString输出XML节点到字符串
/// </summary>
using System;
using System.IO;
using System.Xml.Linq;
namespace DemoOutputString
{
 class Program
{
 static void Main(string[] args)
{
XNamespace sp = "http://www.tiyor.com";
 XElement root = new XElement(sp + "根元素",
 new XAttribute("属性", "0")
 );
 XDocument doc = new XDocument(
 new XDeclaration("1.0","utf-16","yes"),
 new XProcessingInstruction("xml-stylesheet", "type='text/xsl' href='test.xsl'"),
 new XDocumentType("限定名", "Test Name", "专用标识符", "内部子集"),
 new XComment("这是文档的注释内容"), root);
 root.Add(new XElement(sp + "子元素"),
 new XElement(sp + "子元素")
 );
 root.Add(new XCData("这里是根元素的CDATA节点"));
 StringWriter strw = new StringWriter();
 doc.Save(strw, SaveOptions.None);
 strw.Close();
 string strxml = strw.ToString();
 Console.WriteLine(strxml);
 Console.ReadKey();
}
}
}
////// <summary>
///TextWriter
/// </summary>
using System;
using System.Xml.Linq;
namespace DemoOutputTextWriter
{
 class Program
{
 static void Main(string[] args)
{
 XNamespace sp = "http://www.tiyor.com";
 XElement root = new XElement(sp + "根元素",
 new XAttribute("属性", "0")
 );
 XDocument doc = new XDocument(
 new XDeclaration("1.0", "utf8", "yes"),
 new XProcessingInstruction("xml-stylesheet", "type='text/xsl' href='test.xsl'"),
 new XDocumentType("限定名", "Test Name", "专用标识符", "内部子集"),
 new XComment("这是文档的注释内容"), root);
 root.Add(new XElement(sp + "子元素"),
 new XElement(sp + "子元素")
 );
 root.Add(new XCData("这里是根元素的CDATA节点"));
 doc.Save(Console.Out, SaveOptions.None);
 Console.ReadKey();
}
}
}
////// <summary>
///输出XML树倒文件
/// </summary>
using System.Xml;
using System.Xml.Linq;
namespace DemoOutputFile
{
 class Program
{
 static void Main(string[] args)
{
 XNamespace sp = "http://www.tiyor.com";
 XElement root = new XElement(sp + "根元素",
 new XAttribute("属性", "0")
 );
 XDocument doc = new XDocument(
 new XDeclaration("1.0", "utf8", "yes"),
 new XProcessingInstruction("xml-stylesheet", "type='text/xsl' href='test.xsl'"),
 new XDocumentType("限定名", "Test Name", "专用标识符", "内部子集"),
 new XComment("这是文档的注释内容"), root);
 root.Add(new XElement(sp + "子元素"),
 new XElement(sp + "子元素")
 );
 root.Add(new XCData("这里是根元素的CDATA节点"));
 
 doc.Save("test1.xml", SaveOptions.None);
 XmlWriter xw = XmlWriter.Create("test2.xml");
 doc.WriteTo(xw);
 xw.Close();
}
}
}
[/code]
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: