asp.net LINQ to XML hands-on descendants, elements traversal node _ practical Tips

Source: Internet
Author: User
First, prepare a simple but common XML
Copy Code code as follows:

<?xml version= "1.0" encoding= "Utf-8"?>
<userSet>
<userinfo id= "1" name= "Guozhijian" >
<profile>
<phoneNumber>13818181818</phoneNumber>
<country>China</country>
</profile>
</userInfo>
<userinfo id= "2" name= "Zhenglanzhen" >
<profile>
<phoneNumber>13919191919</phoneNumber>
<country>Korea</country>
</profile>
</userInfo>
</userSet>

Test One:
Copy Code code as follows:

private void Test1 ()
{
XDocument Xdoc = xdocument.load (@ "Userset.xml");
var users = from u in Xdoc. Descendants ("UserInfo")
where U.attribute ("id"). Value = = "1"
Select U;
foreach (Var u in users)
{
String name = U.attribute ("name"). Value;
Console.WriteLine (name);
}
}

The output results are:
Guozhijian
Test Two
Copy Code code as follows:

private void Test2 ()
{
XDocument Xdoc = xdocument.load (@ "Userset.xml");
var users = from u in Xdoc. Root.elements ("UserInfo")
where U.element ("Profile"). Element ("PhoneNumber"). Value = = "13919191919"
Select U;
foreach (Var u in users)
{
String name = U.attribute ("name"). Value;
Console.WriteLine (name);
}
}

The output results are:
Zhenglanzhen

Attention:
Descendants can traverse a node or all child nodes under a document
Elements is to traverse the current node or the next level of the document child nodes (this difference is very important)
A very simple two class has basically satisfied the normal XML traversal.
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.