0

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 i m doing mistakes.

3 Answers 3

2
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!!

Sign up to request clarification or add additional context in comments.

Comments

1

Hope this will do trick

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.