Removing unwanted nodes from XML, keep the XML hierarchy same
Lets say we have XML as -
<Hotels>
<Rooms>
<name>Standars</name>
<Type>Deluxe</Type>
<Rate>123123</Rate>
<Amenities>sfds</Amenities>
<Qty>2</Qty>
</Rooms>
<Rooms>
<name>Delux</name>
<Type>Superior</Type>
<Rate>453</Rate>
<Amenities>234</Amenities>
<Qty>5</Qty>
</Rooms>
<Rooms>
<name>Suite</name>
<Type>Superior</Type>
<Rate>3242</Rate>
<Amenities>xdg</Amenities>
<Qty>7</Qty>
</Rooms>
</Hotels>
and we want output as -
<Hotels>
<Rooms>
<name>Standars</name>
<Type>Deluxe</Type>
</Rooms>
<Rooms>
<name>Delux</name>
<Type>Superior</Type>
</Rooms>
<Rooms>
<name>Suite</name>
<Type>Superior</Type>
</Rooms>
</Hotels>
Below is a linq that can help us to get above result.
var document = XDocument.Load("XMLFile1.xml");
List<string> removeNames = new List<string> { "Rate", "Amenities", "Qty"}; //Collection of fields to be removed.
var removeItems = from item in document.Descendants("HotelSummary")
let ritems = item.Elements().Where(i => removeNames.IndexOf(i.Name.ToString()) >= 0)
select ritems;
foreach (var item in removeItems)
{
item.Remove();
}
document.Save("d:\\try.xml");
No comments:
Post a Comment