Get started with descendants and elements

Source: Internet
Author: User

First, prepare a simple but common XML CopyCode The Code is 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 1:
Copy codeThe Code is 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 );
}
}

Output result:
Guozhijian
Test 2
Copy codeThe Code is 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 );
}
}

Output result:
Zhenglanzhen

Note:
Descendants can traverse all subnodes under a node or document
Elements is a subnode that traverses the current node or the next level of the document (the difference is very important)
The two very simple classes basically meet the requirements of common XML traversal.

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.