【问题标题】:Retrieve XSL URL and name in XML file using Java使用 Java 在 XML 文件中检索 XSL URL 和名称
【发布时间】:2011-10-03 17:58:20
【问题描述】:

我有一个像这样的简单 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”?

非常感谢!!

【问题讨论】:

  • 反问:如何在不知道文件名的情况下解析XML文件?

标签: java xml stylesheet


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    使用正则表达式 &lt;\?xml-stylesheet type="text/xsl" href="(.*?)"\?&gt;

    【讨论】:

      猜你喜欢
      • 2010-11-23
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 2021-08-26
      • 1970-01-01
      相关资源
      最近更新 更多