XElement root = XElement.Parse(@"<?xml version='1.0' encoding='utf-8'?> <Items> <Item> <Id>1</Id> <Name>Name1</Name> <Description>Test1</Description> <Children> <Item> <Id>1.1</Id> <Name>Name1.1</Name> <Description>Test1.1</Description> </Item> </Children> </Item> <Item> <Id>2</Id> <Name>Name2</Name> <Description>Test2</Description> </Item> </Items> "); var elements = root.Elements("Item");//root下的第一層Item(Id為1和2)
XElement firstItem = root.Element("Item").Element("Name"); //第一個Item下的Name(Id為1)
var descendants = root.Element("Item").Descendants("Name");//第一個Item下的所有Name(包括Children下的,Id為1和1.1)
var xElements=root.Descendants("Name");//root下的所有子代的Name(Id為1,1.1,2)
var users = XElement.Load("TemplateUser.config").Elements("user");
var user = users.FirstOrDefault();
var Account = user.Element("Account").Value.ToString();
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlStr); //xml字符串轉成xml文檔對象
XDocument xdoc =doc.ToXDocument(); //xmldocument轉成xdoccument 擴展方法
var eventId = xdoc.Document.Root.Element("EventID"); //根節點下的eventid節點
if (eventId != null)
{
MessageBox.Show(eventId.Value); //15
}
擴展方法
public static class XmlDocumentExtensions
{
public static XDocument ToXDocument(this XmlDocument document)
{
return document.ToXDocument(LoadOptions.None);
}
public static XDocument ToXDocument(this XmlDocument document, LoadOptions options)
{
using (XmlNodeReader reader = new XmlNodeReader(document))
{
return XDocument.Load(reader, options);
}
}
}
From:http://www.cnblogs.com/xuejianxiyang/p/5377486.html