Peter Jaloveczki
Peter Jaloveczki

Reputation: 2089

XSLT get type of an attribute from DTD

Given a valid entry in the DTD of a document:

<!ATTLIST name
               id  CDATA    #IMPLIED 
               attribute  ENTITY    #IMPLIED  >

How can I get the type of an attribute during xslt transformation, given the name of the attribute and the node?

For example name/@id = 'CDATA'

and name/@attribute = 'ENTITY'

Thanks in advance!

Upvotes: 2

Views: 381

Answers (2)

Peter Jaloveczki
Peter Jaloveczki

Reputation: 2089

I found out that using Xerxes and Xalan allows a pretty simple implementation for this problem.

First of all extend the stylesheet tag as following:

<xsl:stylesheet xmlns:java="http://xml.apache.org/xalan/java" ....

On the attribute processing template:

<xsl:template match="@*" mode="fix-entity-references">  
    <xsl:param name="is-entity" select="java:com.ovitas.aton.xslt.Util.isEntity(current())"/>

The code of the referenced class:

import org.apache.xerces.dom.DeferredAttrImpl;
import org.apache.xml.dtm.ref.DTMNodeIterator;

public class Util {

        public static boolean isEntity(Object o) {
            try {
                DTMNodeIterator iter = ((DTMNodeIterator) o);
                DeferredAttrImpl attrImpl = (DeferredAttrImpl) iter.getRoot();
                return attrImpl.getTypeName().equals("ENTITY");
            } catch (ClassCastException e) {
                e.printStackTrace();
                return false;
            }
        }
}

Naturally referenced jars must be added to classpath.

System.setProperty("javax.xml.transform.TransformerFactory", "org.apache.xalan.processor.TransformerFactoryImpl");

The code above enables the use of the xalan transformer.

I'll accept the previous upvoted answer, because this solution is obviously based on the use of xalan and xerxes, but I wanted to add this one as well, for future generations. Maybe it will be useful to someone.

Upvotes: 2

David Carlisle
David Carlisle

Reputation: 5652

This information is not part of the Xpath data model and isn't reported by the XML parser to XSLT (in fact you can't in general be sure the parser reads the DTD at all)

If you suspect an attribute is of type ENTITY then you can use unparsed-entity-uri(@name) XPath function added by XSLT 1 and if you get anything other than the empty string there was an unparsed entity of that name (whether or not that attribute was declared to be of ENTITY type)

Upvotes: 5

Related Questions