this is my XML file, I want to keep the email and phone number elements, and delete the rest elements (FirstName - Gender) at the runtime.
<Users>
<User idNumber="651635163">
<email>d@d.d</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>
so the result should be like this
<Users>
<User idNumber="651635163">
<email>d@d.d</email>
<phoneNumber>0528754964</phoneNumber>
</User>
</Users>
I tried using SelectNodes but I was not able to make it work, Thanks in advance!
Check it out.
c#
void Main()
{
const string fileName = @"e:\temp\Sadi.xml";
const string USER = "User";
// list of XML element names to keep
var listOfElements = new List<string> {"email", "phoneNumber"};
XDocument xdoc = XDocument.Load(fileName);
List<XElement> nodes = xdoc.Descendants(USER).ToList();
// Contains() simulates SQL NOT IN clause
nodes.Elements()
.Where(x => !listOfElements.Contains(x.Name.LocalName))
.Remove();
// save back to the file
xdoc.Save(fileName);
}
Another approach to create new xml with only desired elements
var document = XDocument.Load("path to the file");
var users = document.Descendants("User")
.Select(u => new XElement("User", u.Element("email"), u.Element("phoneNumber"))
.ToArray();
var newDocument = new XDocument(new XElement("Users", users));
newDocument.Save("path to the file");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.