I have a requirement where I'd like to have if else statement to check whether a node has attributes or it has just string.
Eg: 1 of the node has 0 File(s) found
and the other has attribs such as <autoincludesystem_info mdate='08/23/2011' mtime='09:51' ampm='PM' filesize='64' filename='AFP_p.tgp' />
Below is a sample of two nodes
<product>
<autoIncludeUser>0 File(s) found</autoIncludeUser>
<autoIncludeSystem>
<autoincludesystem_info mdate='08/23/2011' mtime='09:51' ampm='PM' filesize='64' filename='AFP_p.tgp' />
<autoincludesystem_info mdate='08/23/2011' mtime='09:51' ampm='PM' filesize='3,879' filename='AnalystsExpressionMacros.tgp' />
<autoincludesystem_info mdate='08/23/2011' mtime='09:51' ampm='PM' filesize='475' filename='base64Converter.tgp' />
<autoincludesystem_info mdate='08/23/2011' mtime='09:51' ampm='PM' filesize='<DIR>' filename='codePages' />
</autoIncludeSystem>
<autoIncludeStudio>0 File(s) found</autoIncludeStudio>
<externalLibrarySystem>
<externalLibrarySystem_info mdate='08/23/2011' mtime='09:52' ampm='PM' filesize='196,608' filename='AFPtoXML_DP.dll' />
<externalLibrarySystem_info mdate='08/23/2011' mtime='09:52' ampm='PM' filesize='13,259' filename='ASN1toXSDRunner.jar' />
<externalLibrarySystem>
</product>
How would i identify if a node has just strings or attribs and based on that I can get the values either String
or attrib values
respectively.
You can replace your whole
xsl:choose
instruction with:and then add two templates:
I. Xpath 1.0 solution - use this single XPath expression:
Here is a XSLT-based verification:
when this transformation is applied on the provided XML document (slightly corrected to be made well-formed):
the wanted, correct result is produced:
Explanation We use these facts:
For any string
$s
,substring($s, Infinity)
is the empty string.1 div 0
isInfinity
By definition
number(true())
is1
andnumber(false())
is 0.II. XPath 2.0 solution:
This is much easier in XPath 2.0 because the language has standard
if/then/else
operator.Use:
XSLT 2.0 verification:
when this transformation is applied on the same XML document (above), again the wanted, correct result is produced:
You can do this easily enough using
xsl:choose
- but very often in XSLT, the better way to do conditional processing is to write different template rules to handle the different conditions. So write one template rule withmatch="*[@*]"
to match elements that have attributes, and another withmatch="*[text()]"
to match elements that have textual content.XPath
//*[not(@*)]
will select all elements, which don't have attributes.We can achieve if else by using below code
So here is what I did
My Output