使用 XSLT 从 XML 文档中提取文本内容 [英] Extracting textual content from XML documents using XSLT

查看:61
本文介绍了使用 XSLT 从 XML 文档中提取文本内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何最好使用 XSLT 提取 XML 文档的文本内容.

How it is possible to extract textual content of an XML document preferably using XSLT.

对于这样的片段,

<record>
    <tag1>textual content</tag1>
    <tag2>textual content</tag2>
    <tag2>textual content</tag2>
</record>

想要的结果是:

文字内容,文字内容,文字内容

textual content, textual content, textual content

输出(表格、CSV 等)的最佳格式是什么,其中内容可用于进一步操作,例如文本挖掘?

What's the best format for output (table, CSV, etc,) in which the content be processable for further operation, such as text mining?

谢谢

更新

扩展问题,如何分别提取每条记录的内容.例如,对于以下 XML:

To extend the question, how it’s possible to extract content of each record separately. For example, for the below XML:

<Records>
<record id="1">
    <tag1>textual co</tag1>
    <tag2>textual con</tag2>
    <tag2>textual cont</tag2>
</record>
<record id="2">
    <tag1>some text</tag1>
    <tag2>some tex</tag2>
    <tag2>some te</tag2>
</record>
</Records>

想要的结果应该是这样的:

The desired result should be such as:

(textual co, textual con, textual cont) , (some text, some tex, some te)

或以更好的格式进行进一步处理.

or in better format for further processing operations.

推荐答案

您可以使用以下 XSLT:

You can use the following XSLT:

<xsl:transform version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/">
    <xsl:apply-templates select="//text()"/>
</xsl:template>
<xsl:template match="text()">
    <xsl:value-of select="."/>
    <xsl:if test="position() != last()">, </xsl:if>
</xsl:template>
</xsl:transform>

对于问题中的更新,您可以使用以下 XSLT:

And for the update in the question, you can use the following XSLT:

<xsl:transform version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/*">
    <xsl:apply-templates/>
</xsl:template>
<xsl:template match="*">(<xsl:apply-templates select=".//text()"/>)<xsl:if test="position() != last()">, </xsl:if>
</xsl:template>
<xsl:template match="text()">
    <xsl:value-of select="."/>
    <xsl:if test="position() != last()">, </xsl:if>
</xsl:template>
</xsl:transform>

这篇关于使用 XSLT 从 XML 文档中提取文本内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆