是的,尝试使用TransformerFactory.getAssociatedStylesheet方法:
TransformerFactory factory = TransformerFactory.newInstance();
StreamSource xml = new StreamSource("input.xml");
Source xsl = factory.getAssociatedStylesheet(xml, null, null, null);
System.out.println(new File(xsl.getSystemId()).getName());
返回值:
01C3_OIZODEMO_certificato_v1.0.xsl
另一种方法是:
SAX API:
SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
saxParser.parse("input.xml", new DefaultHandler()
{
@Override
public void processingInstruction(String target, String data)
throws SAXException
{
if (target.equals("xml-stylesheet"))
{
Pattern pattern = Pattern.compile("href=\"(.+)\"");
Matcher matcher = pattern.matcher(data);
if (matcher.find())
System.out.println(matcher.group(1));
}
}
});
DOM API:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse("input.xml");
XPathFactory pathFactory = XPathFactory.newInstance();
XPath path = pathFactory.newXPath();
XPathExpression expression =
path.compile("//processing-instruction('xml-stylesheet')");
ProcessingInstruction instruction =
(ProcessingInstruction) expression.evaluate(doc, XPathConstants.NODE);
Pattern pattern = Pattern.compile("href=\"(.+)\"");
Matcher matcher = pattern.matcher(instruction.getData());
if (matcher.find())
System.out.println(matcher.group(1));
在两种情况下,结果都是相同的:
01C3_OIZODEMO_certificato_v1.0.xsl