Query xml and linqxml by using linq
1. Load the xml string
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> <Id> 2 </Id> <Name> Name2 </Name> <Description> Test2 </Description> </Item> </Items> "); var elements = root. elements ("Item"); // The first Item (Id: 1 and 2) under root)
XElement firstItem = root. Element ("Item"). Element ("Name"); // Name (Id: 1) under the first Item)
Var descendants = root. Element ("Item"). Descendants ("Name"); // all names under the first Item (including the IDs of 1 and 1.1 in Children)
Var xElements = root. Descendants ("Name"); // Name of all the children under root (Id: 1, 1.1, 2)
2. Directly load the file:
Var users = XElement. Load ("TemplateUser. config"). Elements ("user ");
Var user = users. FirstOrDefault ();
Var Account = user. Element ("Account"). Value. ToString ();
3. Convert XmlDocument to XDocument
XmlDocument doc = new XmlDocument ();
Doc. LoadXml (xmlStr); // convert an xml string to an xml Document Object
XDocument xdoc = doc. ToXDocument (); // convert xmldocument to xdoccument Extension Method
Var eventId = xdoc. Document. Root. Element ("EventID"); // eventid node under the Root node
If (eventId! = Null)
{
MessageBox. Show (eventId. Value); // 15
}
Extension Method
Public static class xmlbeanentextensions
{
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