使用Java检索XML文件中的XSL URL和名称

时间:2011-07-12 15:25:14

标签: java xml stylesheet

我有一个像这样的简单XML文件:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="01C3_OIZODEMO_certificato_v1.0.xsl"?>
<Certificato>
    <TD:Global xmlns:TD="http://www.xxxx.org/TD_tags">
        <TD:XSL_Def>
            <TD:orig>http://www.xxxx.com/xsl/</TD:orig>
        </TD:XSL_Def>
    </TD:Global>
    <TipoCert>Stato civile</TipoCert>
    <Nominativo>Fenil Postume</Nominativo>
    <DatiNascita>
        <DataNas>01/01/2099</DataNas>
        <Luogo>Perengana</Luogo>
        <Atto>Atto n. 735 p.1 s.A u. 1</Atto>
    </DatiNascita>
    <Indirizzo>
        <Via>Via Perengana</Via>
        <NumeroCivico>0</NumeroCivico>
        <Cap>99999</Cap>
        <Frazione>NA</Frazione>
    </Indirizzo>
    <Testo>TEST</Testo>
    <Data>22/12/2010</Data>
    <Ora>10:48:00</Ora>
</Certificato>

如何使用Java中的xml API检索文件名“01C3_OIZODEMO_certificato_v1.0.xsl”?

非常感谢!!

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:0)

使用正则表达式 <\?xml-stylesheet type="text/xsl" href="(.*?)"\?>