CSCI 5931A.1
XML Application Development
Spring 2002
Suggested Solution to Final Examination
(1)
(a) For example,
(b) The root element.
(2) For example,
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:output method="xml" version="1.0" indent="yes" />
<xsl:template match='/'>
<xsl:apply-templates />
</xsl:template>
<xsl:template match='*'>
<xsl:copy>
<xsl:attribute name="numAttributes"><xsl:value-of
select="count(@*)" /></xsl:attribute>
<xsl:apply-templates />
</xsl:copy>
</xsl:template>
<xsl:template match='text()|@*' />
</xsl:stylesheet>
(3) For example,
private static int getElementWithCommentCount(Element
element)
{ // Whether element contains comments.
boolean hasTopLevelComments = false;
int result = 0;
if (element == null) return 0;
// Loop through children nodes to sum up
their counts.
int i = 0;
NodeList childNodes = element.getChildNodes();
int numChildNodes = childNodes.getLength();
for (i=0; i< numChildNodes; i++)
{ short nodeType = childNodes.item(i).getNodeType();
if (nodeType == Node.ELEMENT_NODE)
{
int childElementWithCommentCount
= getElementWithCommentCount((Element) childNodes.item(i));
if (childElementWithCommentCount
> 0) {
result += childElementWithCommentCount;
hasTopLevelComments = true;
}
}
else {
if (nodeType
== Node.COMMENT_NODE) {
hasTopLevelComments = true;
}
}
}
// Add the current element to the
count.
if (hasTopLevelComments) result++;
return result;
} // getElementWithCommentCount