using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
var xDoc = new XDocument(
new XElement("root", new XElement("item", new XAttribute("color", "blak1"), new XElement("dog", new XText("dog said black is a beautiful color"), new XAttribute("color", "blak1")
), new XElement("cat"), new XElement("pig", "pig is great")
)
,
new XElement("item", new XAttribute("color", "blak1"), new XElement("dog", new XText("dog said black is a beautiful color"), new XAttribute("color", "blak2")
), new XElement("cat"), new XElement("pig", "pig is great")
),
new XElement("item", new XAttribute("color", "blak1"), new XElement("dog", new XText("dog said black is a beautiful color"), new XAttribute("color", "blak3")
), new XElement("cat"), new XElement("pag", "pig zwj is great", new XAttribute("id", "zwj"))
)
)
);
xDoc.Save("1.xml");
// Descendants 可以遍历节点下面的所有的子节点和节点 [不包括本身]
// Elements 只能遍历下来的子节点
XDocument dco = XDocument.Load("a.xml");
var temp = dco.Elements("rss").Elements("channel");
// 用Elements 遍历
foreach (XElement item in dco.Descendants("item"))
{
Console.WriteLine("标题是:{0}-{1}", item.Element("title").Value == null ? "空置" : item.Element("title").Value, item.Element("title").Name);
}
// 用Descendants 遍历
foreach (XElement item in dco.Descendants("item"))
{
Console.WriteLine("标题是:{0}-{1}", item.Element("title").Value == null ? "空置" : item.Element("title").Value, item.Element("title").Name);
}
// 结合linq 查询
IEnumerable<XElement> xl = from item in dco.Descendants("root")
where item.Attribute("color").Value == "blak1"
select item;
foreach (XElement item in xl)
{
Console.WriteLine(item.Element("pag").Value);
}
Console.WriteLine("zwj");
Console.ReadKey();
}
}
}