سؤال

I have the following xml:

<?xml version="1.0" encoding="UTF-8"?>
<response>
   <folder>
      <TestOne>F</TestOne>
      <TestTwo>01</TestTwo>
      <case>
         <CRDATTIM>2014-03-26-05.22.22.339840</CRDATTIM>
         <RECORDCD>C</RECORDCD>
      </case>
      <case>
         <CRDATTIM>2014-03-26-05.05.51.531840</CRDATTIM>
         <RECORDCD>C</RECORDCD>
      </case>
   </folder>
</response>

I need the XPath expression to read the nodes and their values immediately under the <folder> tag. I don't require the child nodes information. I mean, my extracted info should look like below:

<folder>
<TestOne>F</TestOne>
<TestTwo>01</TestTwo>
<folder>

Here the tags names listed under <folder>i.e <TestOne>, <TestTwo> are dynamic.

Is there any way to derive an XPath expression for above requirement? Please let me know if my question is not clear. Thanks in advance.

هل كانت مفيدة؟

المحلول 2

XPath is a way to select particular nodes out of an XML tree, but on its own it can't change the content of any of those nodes. If you use an expression to select the folder element

/response/folder

then you'll get the whole of that element, including the case children. You could select just the "leaf" elements under folder using

/response/folder/*[not(*)]

which would give you a node set containing two elements (the TestOne and the TestTwo), but assembling those two elements into a new folder element is not something XPath can do for you. You'll have to do that yourself using whatever facilities are provided by the language/tool you're using to evaluate the XPath expressions.

نصائح أخرى

Here's a template that will output only direct childs of a <folder> node:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" exclude-result-prefixes="xsl">
    <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
    <xsl:template match="/response/folder">
        <folder>
            <xsl:apply-templates select="node()" mode="childs"/>
        </folder>
    </xsl:template>
    <xsl:template match="*" mode="childs">
        <xsl:if test="count(./text()) = 1">
            <xsl:element name="{local-name()}">
                <xsl:value-of select="."/>
            </xsl:element>
        </xsl:if>
    </xsl:template>
</xsl:stylesheet>

If you're just after the xpath to get all those nodes within your folder node:

/response/folder/node()[count(text()) = 1]

Did you try the count method?

/response/folder/*[count(*)=0]
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top