LINQ之路二:TO XML(2)
参考文档:http://www.cnblogs.com/lifepoem/archive/2011/12/06/2277554.html
一:X-DOM介绍

二:XElement包含了管理属性的方法,以及Name和Value成员。
using System.Xml.Linq;
XElement lastName = new XElement("lastname", "Bloggs");
//他会创建这样的节点 <lastname>Bloggs</lastname>
XElement StuClass = new XElement("Class");
XElement Student = new XElement("Student", "小明");
StuClass.Add(Student);
Console.WriteLine(StuClass.ToString());
//<Class>
// <Student>小明</Student>
//</Class>
//增加属性
//< Body >
// < Student Age = "15" Sex = "男" Name = "小明" />
//</ Body >
XElement StuClass = new XElement("Body");
XElement Student = new XElement("Student");
XAttribute[] parm = new XAttribute[]
{
new XAttribute("Age", 15),
new XAttribute("Sex", "男"),
new XAttribute("Name", "小明")
};
Student.Add(parm);
StuClass.Add(Student);
Console.WriteLine(StuClass.ToString());
三:XDocumentXelement和XDocument都提供了静态的Load和Parse方法,他们用来创建X-DOM tree。Load用来从file、URI、Stream、TextReader或XmlReader创建X-DOM
Parse用来从string创建X-DOM
XDocument doc = XDocument.Load(string url);
XElement config = XElement.Parse(
@"<configuration>
<client enabled='true'>
<timeout>30</timeout>
</client>
</configuration>");
四:简单例子
IEnumerable<XElement> ChildElements= XElement.Elements();//XElement下的子元素
XDocument xd = new XDocument(
new XElement("MyElement",
new XElement("first",
new XAttribute("color","red"),
new XAttribute("size", "small")
),
new XElement("second",
new XAttribute("color", "red"),
new XAttribute("size", "medim")
),
new XElement("third",
new XAttribute("color", "blue"),
new XAttribute("size", "large")
)
)
);
XElement root = xd.Element("MyElement");
var query = from e in root.Elements()
where e.Name.ToString().Length == 5
select e;
foreach(XElement q in query)
{
Console.WriteLine("Name:{0},color:{1},size:{2}",
q.Name,
q.Attribute("color").Value,
q.Attribute("size").Value
);
}

例子2

using System.Xml.Linq;
private void LoadXmlByLinq()
{
XDocument xml = XDocument.Load(@"d:\test.xml");
XElement root = xml.Element("Students");//获取第一个子节点
var node = from e in root.Elements()//遍历根节点下的节点
where Convert.ToInt32(e.Attribute("age").Value)>21
select e;
string s = "";
foreach (XElement xnode in node)
{
s += xnode.Attribute("age").Value;
s += xnode.Attribute("name").Value;
}
MessageBox.Show(s);//22魅族
}

浙公网安备 33010602011771号