删除C#中XML文件中的特定元素

问题描述 投票:0回答:2

这是我的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,但无法使其正常工作,谢谢!!

c# xml linq-to-xml
2个回答
0
投票
另一种只用所需元素创建新xml的方法

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");


0
投票
签出。
© www.soinside.com 2019 - 2024. All rights reserved.