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.