首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用XSLT将特殊字符保留为输出

使用XSLT将特殊字符保留为输出
EN

Stack Overflow用户
提问于 2017-09-13 14:47:50
回答 3查看 1.3K关注 0票数 1

我面临的问题是,即使在XSLT转换之后,也要保留特殊字符。我的源文件XHTML文件包含几个特殊字符,如 —’;在XSLT转换时,这些字符将被忽略。

我尝试过各种不同的答案,比如

如果我手动将特殊字符的值更改为相应的Unicode表示,则这些字符将保留在输出中。

例如,将 转换为 ,它会在输出中产生一个空格。请参阅下面的一些样本文件:

源XHTML :

代码语言:javascript
运行
复制
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:text="http://giraffe.wkle.com/text" xmlns:epub="http://www.idpf.org/2007/ops">
    <body>
        <div class="section" id="section_1">
            <p id="para_1" class="para">Content&nbsp;of&nbsp;paragraph&mdash;1.</p>
            <p id="para_2" class="para">Content&nbsp;of&nbsp;paragraph&mdash;2.</p>
        </div>
    </body>
</html>

XSL模板:

代码语言:javascript
运行
复制
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema">

    <xsl:output method="xml" indent="yes"/>
    <xsl:template match="node()|@*" name="identity">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*" />
        </xsl:copy>
    </xsl:template>

    <xsl:template match="*[local-name()='p']/text()">
        <xsl:copy-of select="."/>
    </xsl:template>
</xsl:stylesheet>

预期输出:

代码语言:javascript
运行
复制
<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops" xmlns:text="http://giraffe.wkle.com/text">
    <body>
        <div class="section" id="section_1">
            <p class="para" id="para_1">Content of paragraph—1.</p>
            <p class="para" id="para_2">Content of paragraph—2.</p>
        </div>
    </body>
</html>

实际输出:

代码语言:javascript
运行
复制
<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops" xmlns:text="http://giraffe.wkle.com/text">
    <body>
        <div class="section" id="section_1">
            <p class="para" id="para_1">Contentofparagraph1.</p>
            <p class="para" id="para_2">Contentofparagraph2.</p>
        </div>
    </body>
</html>

限制:

  1. 我没有修改源XHTML内容或其DTD的权限。
  2. XSLT的版本是1.0。

请告诉我是否有任何方法可以使用Unicode值转换特殊字符并将它们保留在我的输出XML文档中。

更新:

我使用这段Java代码来调用转换:

代码语言:javascript
运行
复制
public class XSLTUtil {

    public static String processXHTML(String sourceFileName, String outputXhtml, String xslFilePath) throws ParserConfigurationException, SAXException, IOException, TransformerException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docbuilder = factory.newDocumentBuilder();
        Document doc = docbuilder.parse(new FileInputStream(sourceFileName));

        FileOutputStream fos = null;
        FileInputStream fis = null;
        try {
            fos = new FileOutputStream(outputXhtml);
            fis = new FileInputStream(xslFilePath);
            TransformerFactory transformfactory = TransformerFactory.newInstance();
            Templates xsl = transformfactory.newTemplates(new StreamSource(fis));
            Transformer transformer = xsl.newTransformer();
            transformer.transform(new DOMSource(doc.getDocumentElement()),new StreamResult(fos));
            return outputXhtml;
        } finally {
            if(fos != null) {
                fos.close();
            }
            if(fis != null) {
                fis.close();
            }
        }
    }

    public static void main(String args[]){
        String sourceFileName = "C:\\source.xhtml";
        String outputXhtml = "C:\\output.xhtml";
        String xslFilePath = "C:\\xslTemplate.xsl";
        String result = "-1";
        try {
            result = processXHTML(sourceFileName, outputXhtml, xslFilePath);
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
        System.out.println("Result : "+ result);
    }
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-09-14 14:57:51

使用Apache Lang3 Lang3 StringEscapUtils的解决方案。需要图书馆:

代码语言:javascript
运行
复制
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.0</version>
    </dependency>

首先阅读内容并将所有实体替换为真实文本。

代码语言:javascript
运行
复制
public static String processXHTML(String sourceFileName, String outputXhtml,
        String xslFilePath) throws ParserConfigurationException, SAXException, IOException,
        TransformerException {

    Charset charset = StandardCharsets.UTF_8;
    Path path = Paths.get(sourceFileName);
    String source = new String(Files.readAllBytes(path), charset);
    source = source.replaceAll("\\&(amp|lt|gt|quot);", "\u0001$1;");
    source = StringEscapeUtils.unescapeHtml4(source);
    source = source.replace('\u0001', '&');
    byte[] bytes = source.getBytes(charset);
    ByteArrayInputStream bais = new ByteArrayInputStream(bytes);

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docbuilder = factory.newDocumentBuilder();
    docbuilder.setEntityResolver(new EntityResolver() {
        @Override
        public InputSource resolveEntity(String publicId, String systemId)
                    throws SAXException, IOException {
            System.out.printf("resolveEntity PUBLIC %s SYSTEM %s%n", publicId, systemId);
            return new InputSource(new StringReader(""));
        }
    });
    //Document doc = docbuilder.parse(new FileInputStream(sourceFileName));
    Document doc = docbuilder.parse(bais);

我跳过了XML实体。

我用短线连接了EntityResolver,因为读取和处理实体(通过网络)需要很长时间。似乎您已经安装了类似的东西,因为实体没有被替换。

在resolveEntity中,返回null以查看哪些DTD是递归加载的。

或者,您可以安装一个HTML目录,这是HTML的本地缓存,其中有一些。

票数 1
EN

Stack Overflow用户

发布于 2017-09-13 16:20:44

对较早版本的问题的过时回答

考虑使用Andrew的Lexev实用程序。它基本上对XML进行预处理,将实体引用转换为将通过XML解析保留的内容,然后对转换结果进行后处理以将实体引用放回。

http://andrewjwelch.com/lexev/

票数 0
EN

Stack Overflow用户

发布于 2017-09-14 13:54:22

我会处理掉DOM代码。当您只想将DOM转换为其他东西时,创建DOM是笨拙和低效的。如果您提供一个StreamSource或SAXSource,并让它们决定自己的树表示形式,那么Saxon和Xalan都会运行得更快。与撒克逊,这可以是5-10倍的速度,将使用更少的内存。

我不知道DOM为什么会丢失实体引用。对于所使用的XSLT处理器,您提供了相互矛盾的信息,因此不容易进行研究,但是由于DOM数据模型不同于XSLT/XPath数据模型(特别是在处理实体扩展方面),因此应该解决这个问题。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46200610

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档