locked
remove empty elemets with no attributes RRS feed

  • Question

  • I remove all the empty elemets, but  it erase the elemets with attributes ??

    Any idea how to remove only elemts but with no attributes

    Wednesday, August 26, 2009 4:25 PM

Answers

  • As the DOM implementation in .NET supports XPath 1.0 we can simply 'translate' the match pattern in the XSLT stylesheet into an XPath expression:

    XmlDocument doc = new XmlDocument();
    doc.Load("input.xml");
    foreach (XmlNode node in doc.SelectNodes("//*[not(node()) and not(@*)]"))
    {
      node.ParentNode.RemoveChild(node);
    }
    doc.Save("output.xml");

    MVP XML My blog
    Wednesday, August 26, 2009 5:39 PM

All replies

  • Please provide some details, do you use or want to use XSLT or DOM (XmlDocument) or LINQ to XML (XDocument)?
    With XSLT you could do e.g.

    <xsl:stylesheet
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
      version="1.0">
    
      <xsl:template match="@* | node()">
         <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
         </xsl:copy>
      </xsl:template>
    
      <xsl:template match="*[not(node()) and not(@*)]"/>
    
    </xsl:stylesheet>
    to remove the elements with no contents and no attributes.
    MVP XML My blog
    Wednesday, August 26, 2009 4:56 PM
  • Thanks I  want to use DOM(XMLDocument) C#  or VB
    Wednesday, August 26, 2009 5:03 PM
  • As the DOM implementation in .NET supports XPath 1.0 we can simply 'translate' the match pattern in the XSLT stylesheet into an XPath expression:

    XmlDocument doc = new XmlDocument();
    doc.Load("input.xml");
    foreach (XmlNode node in doc.SelectNodes("//*[not(node()) and not(@*)]"))
    {
      node.ParentNode.RemoveChild(node);
    }
    doc.Save("output.xml");

    MVP XML My blog
    Wednesday, August 26, 2009 5:39 PM
  • thank you very much
    Wednesday, August 26, 2009 8:36 PM