简体   繁体   中英

How to delete nodes from XML with exact string match in c#

I have below xml. I want to delete those nodes which doesn't contains attributes. in below xml I want to delete last 4 nodes which doesn't have attributes.

XML

<products>
    <product system="kn-movies" code="UR">Unrated</product>
    <product system="mu-movies" code="UR">Unrated</product>
    <product system="na-movies" code="UR">Unrated</product>
    <product system="fj-movies" code="UR">Unrated</product>
    <product>Unrated (Unrated )</product>
    <product>Unrated (Unrated )</product>
    <product>Unrated (Без классификации )</product>
    <product>Unrated (غير مصنف )</product>
</products>

I had tried this c# code

var ratingNode = document.Descendants("rating").Where(t => t != null && t.Equals(Convert.ToString(nodeItem))).FirstOrDefault();
                            if (ratingNode != null)
                            {
                                ratingNode.Remove();
                            }

but it doesn't worked for me. please help me out where im doing mistakes.

System.Xml.Linq.XDocument doc = System.Xml.Linq.XDocument.Load(filepath);
var newList = doc.Root.Descendants().ToList().RemoveAll(x => x.Attributes() == null || x.Attributes().Count() <= 0);

Hope it helps!!

Hope this will do trick

XmlNodeList nodes = xmlDocument.GetElementsByTagName("products");
foreach(XmlNode node in nodes)
{
    if(node.Attributes.Count == 0)
    {
        node.RemoveAll;
    }
}

You could use Linq to Xml and query for elements which has no attributes, then you just need Remove call to remove those elements.

XDocument doc = XDocument.Load(filepath);       
doc.Root
   .Descendants()                             // flattens the structure 
   .Where(x=> x.Attributes().Count() <= 0)     // filter elements which has no attributes
   .Remove();                                 // Remove them 

Check this Demo

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM