首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将非结构化xml转换为结构化

将非结构化xml转换为结构化
EN

Stack Overflow用户
提问于 2016-07-19 10:27:19
回答 1查看 490关注 0票数 1

我有一个非结构化XML,它必须转换为结构化XML。我是从apache解析并由Parscit转换为xml的科学pdf文件中获得这个结果的。xml如下所示:

输入

代码语言:javascript
复制
<algorithm>
    <sectionHeader> Section1 </sectionHeader>
    <BodyText>Text goes here</BodyText>
    <sectionHeader> Section2 </sectionHeader>
    <BodyText>Text goes here</BodyText>
    <subsectionHeader>Subsection</subsectionHeader>
    <BodyText>Text goes here</BodyText>
    <sectionHeader> Section1 </sectionHeader>
    <BodyText>Text goes here</BodyText>
</algorithm>

输出

代码语言:javascript
复制
<algorithm>
    <sectionHeader> 
        <Text> Section1 </Text>
        <BodyText>Text goes here</BodyText>
    </sectionHeader>
    <sectionHeader> 
       <Text> Section2 </Text>
       <BodyText>Text goes here</BodyText>
    <subsectionHeader>
        <Text>Subsection</Text>
        <BodyText>Text goes here</BodyText>
    </subsectionHeader>
</sectionHeader>
<sectionHeader> 
    <text>Section3 </Text>
    <BodyText>Text goes here</BodyText>
</sectionHeader>
</algorithm>

我可以使用java中的和xpath来完成这个任务。但它会影响性能,因为我可能需要处理数百万份文档。那么,xslt是一个更好的方法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-07-19 10:48:36

你可以这样做:

XSLT2.0

代码语言:javascript
复制
<xsl:stylesheet version="2.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="utf-8" indent="yes"/>

<xsl:template match="/algorithm">
    <xsl:copy>
        <xsl:for-each-group select="*" group-starting-with="sectionHeader">
            <sectionHeader> 
                <Text>
                    <xsl:value-of select="." />
                </Text>
                <xsl:for-each-group select="current-group()" group-starting-with="subsectionHeader">
                    <xsl:choose>
                        <xsl:when test="self::subsectionHeader">
                            <subsectionHeader> 
                                <Text>
                                    <xsl:value-of select="." />
                                </Text>
                                <xsl:copy-of select="current-group()[not(self::subsectionHeader)]"/>
                            </subsectionHeader> 
                        </xsl:when>
                        <xsl:otherwise>
                            <xsl:copy-of select="current-group()[not(self::sectionHeader)]"/>
                        </xsl:otherwise>
                    </xsl:choose>
                </xsl:for-each-group>
            </sectionHeader>
        </xsl:for-each-group>
    </xsl:copy>
</xsl:template>

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

https://stackoverflow.com/questions/38455906

复制
相关文章

相似问题

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