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.