java url xml文件_使用Java检索XML文件中的XSL URL和名称

是的,尝试使用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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值