.Net中的System.Xml.Linq命名空间提供了linq to xml的支持。这个命名空间中的XDocument,XElement以及XText,XAttribute提供了读写xml文档的关键方法。 1. 使用linq to xml写xml: 使用XDocument的构造函数可以构造一个Xml文档对象;使用XElement对象可以构造一个xml节点元素,使用XAttribute构造函数可以构造元素的属性;使用XText构造函数可以构造节点内的文本。 如下实例代码: 复制代码 代码如下: class Program { static void Main(string[] args) { var xDoc = new XDocument(new XElement( "root", new XElement("dog", new XText("dog said black is a beautify color"), new XAttribute("color", "black")), new XElement("cat"), new XElement("pig", "pig is great")));
上面代码将输出如下Xml: 复制代码 代码如下: <?xml version="1.0" encoding="gb2312"?> <root> <dog color="black">dog said black is a beautify color</dog> <cat /> <pig>pig is great</pig> </root>
可以看出linq to xml比XmlDocument和XmlWriter要方便很多。 2. 使用linq to xml 读取xml Linq是从集合中查询对象,在linq to xml中的集合是通过XElement的Elements(),Elements(string name),以及Descendants、DescendantsAndSelf、Ancestors、AncestorsAndSelf的几个重载方法中获得。 获得XElement集合之后,可以通过XElement的Attribute(string name)方法获得元素的属性值,可以通过XElement的Value属性获得节点的文本值;使用linq就可以方便的做查询,做筛选排序了 还是上例中的xml,我们要读取root的所有字节点,并打印出来,如下代码: 复制代码 代码如下: class Program { static void Main(string[] args) {
var xDoc = new XDocument(new XElement( "root", new XElement("dog", new XText("dog said black is a beautify color"), new XAttribute("color", "black")), new XElement("cat"), new XElement("pig", "pig is great")));
var query = from item in xDoc.Element( "root").Elements() select new { TypeName = item.Name, Saying = item.Value, Color = item.Attribute("color") == null?(string)null:item.Attribute("color").Value };
foreach (var item in query) { Console.WriteLine("{0} "s color is {1},{0} said {2}",item.TypeName,item.Color??"Unknown",item.Saying??"nothing"); }