locked
XPath Get only node without child nodes RRS feed

  • Question

  • Hi, everybody!
    I want to know if there is a way to resolve my problem.
    So I want with xpath to get only nodes without their child nodes.
    My xml is:
    <ts>
    <uc>
        <Questions>
            <q  />
            <q  />
        </Questions>
    </uc>
    <uc>
        <Questions>
            <q  />
            <q  />
            <q  />
        </Questions>
    </uc>
    </ts>
    So I want the following result:
    <ts>
    <uc>
    </uc>
    <uc>
    </uc>
    </ts>

    As you see I want only uc nodes without their children Question nodes.
    I need an urgent help.
    So any your answer would be highly appreciated by me.
    Thanks in advance!
    Monday, December 7, 2009 10:27 AM

Answers

  • XPath selects nodes in the XML input documents, it does not modify that document. Thus if you use an XPath expression like
    /ts/uc
    then you select the 'uc' child elements of the 'ts' root element in your posted XML input document and the 'uc' elements you select of course continue to have their child and descendants elements (like Questions and q elements).
    If you want to remove those child and descendant elements then one way is to use XSLT to transform your XML input document to a result document:

    <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="uc">
         <xsl:copy/>
      </xsl:template>
    
    </xsl:stylesheet>
    You can apply such an XSLT stylesheet in the .NET framework with System.Xml.XslCompiledTransform.
    MVP XML My blog
    Monday, December 7, 2009 11:32 AM