Query xml and linqxml by using linq

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.