1
votes

I have an XML file which references an associated XSL file, like this:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="my-transform.xsl"?>

<my-root> .....

and I want to read it in as a org.w3c.dom.Document, applying the transform.

I'm considering reading it in, extracting the stylesheet processing-instruction using XPATH /processing-instruction('xml-stylesheet') and then loading the XSL file by hand and applying it with a Transformer.

But it seems odd that I need to do this manually - is there a neat way to read the file and apply the embedded transform automatically?

UPDATE: thanks to @raphaëλ for observing that TransformerFactory.getAssociatedStylesheet(...) will identify the xml-stylesheet value as a Source, which is pretty close. Is there anything more automatic than that?

1
Is it necessary to embed XSL in XML or any other approach is okay? - nawazlj
you can use getAssociatedStylesheet(docs.oracle.com/javase/8/docs/api/javax/xml/transform/…) to obtain the Source - raphaëλ
@nawazlj Ideally, the XML should specify the stylesheet, because actually the XML is written by my downstream client users. I'm selling them the idea of customizing (read reducing massive duplication!) their XML by letting them give me XSLT files too, so they can develop their own shorthands and ship them to me along with the XML. In fact, they've already developed their shorthand, but it's in their build process and I'm trying to bring it in as part of my service to them. So their XML has to say which of their stylesheets I have to apply, if that makes sense. - SusanW
@rparree Ok, I hadn't seen that - it's far cleaner than my nasty xpath thing, thanks! :-) - SusanW

1 Answers

0
votes

Ok, nobody else answered, and I know the answer now. Stylesheets are not applied automatically. But you can get hold of the stylesheet using TransformerFactory.getAssociatedStylesheet(...), which will identify the xml-stylesheet value as a Source. You can then apply it manually.

Thanks to raphaëλ for pointing this out.