【问题标题】:I am getting exception in XSLT saxon parser我在 XSLT 撒克逊解析器中遇到异常
【发布时间】:2021-12-22 01:45:12
【问题描述】:

我为 saxen 解析器添加了 maven 依赖项,然后将 xml 和 xsl 作为字符串参数发送到 saxonTransform(String xml, String xsl)。但是遇到了一些异常。

<!-- https://mvnrepository.com/artifact/net.sf.saxon/Saxon-HE -->
<dependency>
<groupId>net.sf.saxon</groupId>
<artifactId>Saxon-HE</artifactId>
<version>10.6</version>
</dependency>

SAXON TRANSFORMER(XSLT) 代码:

public static String saxonTransform(String xml, String xsl) throws TransformerException, FileNotFoundException {

String result = "";

System.setProperty("javax.xml.parsers.SAXParserFactory", "org.apache.xerces.jaxp.SAXParserFactoryImpl");

System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");

StringWriter out = new StringWriter();

TransformerFactory tFactory = TransformerFactory.newInstance();

tFactory.setAttribute(FeatureKeys.DTD_VALIDATION, false);

StreamSource xmlSource = new StreamSource(new StringReader(xml));

StreamSource xslSource = new StreamSource(new StringReader(xsl));

StreamResult xmlResult = new StreamResult(out);

Transformer transformer = tFactory.newTransformer(xslSource);

transformer.transform(xmlSource, xmlResult);

result = out.toString();

return result;

}

但是,给定的行无法转换 xml:

Transformer transformer = tFactory.newTransformer(xslSource);

给出如下错误:

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception
[Handler dispatch failed; nested exception is javax.xml.parsers.FactoryConfigurationError:
Provider org.apache.xerces.jaxp.SAXParserFactoryImpl not found] with root cause

【问题讨论】:

  • 为什么需要org.apache.xerces.jaxp.SAXParserFactoryImpl?不能使用 JRE/JDK 的默认 SAX 解析器吗?如果您需要 Xerces,是否也将其添加为依赖项?
  • 我们需要 org.apache.xerces.jaxp.SAXParserFactoryImpl 因为 SAX 解析器(jdk,jre)不能使用我们的 xsl 样式表。然后我为 Saxon-Parsor 添加了 maven 依赖项。
  • 如果 JDK 解析器“不工作”,那么最好找出问题所在,而不是尝试不同的解析器。失败的原因是什么?

标签: java xml xslt saxon


【解决方案1】:

在这一行

System.setProperty("javax.xml.parsers.SAXParserFactory",
    "org.apache.xerces.jaxp.SAXParserFactoryImpl");

您是说您想使用 Apache Xerces 作为您的 XML 解析器,但看起来它在类路径中不可用。

(请注意,对于当今的大多数用途,使用 JDK 中内置的 Xerces 版本效果很好。曾经有一段时间 JDK 版本存在一些令人讨厌的错误,但这似乎已在不久前得到修复。 )

【讨论】:

  • 嗨迈克尔,那么我如何在类路径中添加这个属性?
  • 这取决于您工作的环境。在 Servlets 的堆栈跟踪中提到了某种应用程序服务器。它们都有不同的设置类路径的方法(我对它们都不是很熟悉)。但是由于您为 Saxon 添加了一个 Maven 依赖项,也许您也应该为 Apache Xerces 添加一个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-25
  • 1970-01-01
  • 2013-12-29
  • 1970-01-01
  • 1970-01-01
  • 2012-05-26
  • 2011-11-06
相关资源
最近更新 更多