这是我的XML文件,我想保留电子邮件和电话号码元素,并在运行时删除其余元素(名字-性别)。
<Users>
<User idNumber="651635163">
<email>[email protected]</email>
<phoneNumber>0528754964</phoneNumber>
<FirstName>kujygv</FirstName>
<LastName>uyf</LastName>
<FatherName>uyfy</FatherName>
<MotherName>uyf</MotherName>
<GfatherName>uyf</GfatherName>
<DateOfBirth>06/04/1999</DateOfBirth>
<ImagePath>C:\Users\m\Desktop\pictures\me\meirl.jpg</ImagePath>
<Address>fyu</Address>
<Gender>זכר</Gender>
</User>
</Users>
所以结果应该像这样
<Users>
<User idNumber="651635163">
<email>[email protected]</email>
<phoneNumber>0528754964</phoneNumber>
</User>
</Users>
我尝试使用SelectNodes,但无法使其正常工作,谢谢!!
var document = XDocument.Load("path to the file");
var names = new[] {"email", "phoneNumber"}.ToHashSet();
var users = document.Descendants("User")
.Select(user => new XElement("User",
user.Where(element => names.Contains(element.Name)).ToArray())
)
.ToArray();
var newDocument = new XDocument(new XElement("Users", users));
newDocument.Save("path to the file");