将 XML 转换为指定的顺序 (DTD -> XSD) [英] Transform XML into specified ordering (DTD -> XSD)

查看:29
本文介绍了将 XML 转换为指定的顺序 (DTD -> XSD)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个项目,其中我们正在处理的主文件是一个旧的 XML 文件,其中创建者制作了一个非常非结构化的 DTD(所有元素都是可选的,可以出现 0 次或多次.更好的是读取文件的应用程序实际上需要许多值).我根据已知的应用程序需求创建了一个 XSD,并将无序元素列表移动到 XSD 中的序列中.

I have a project where the main file we are dealing with is an old XML file where the creator made a very unstructured DTD (All elements are optional, and can occur 0 or more times. Even better the application which reads the file actually expects many of the values as required). I have created an XSD based upon known application requirements, and moved the unordered element lists into sequences in the XSD.

是否有一个简单的转换过程(例如 XSLT)可以采用旧的 XML 文件,并以指定的方式对其元素进行排序,以便我们可以使用新的 XSD 对其进行验证?

Is there an simple transformation process (e.g. XSLT) which can take an old XML file, and order its elements in a specified way so that we can use the new XSD to validate it?

示例:

<Top>
  <A/>
  <D/>
  <B/>
  <C/>
  <A/>
</TOP>

进入

<Top>
  <A/>
  <A/>
  <B/>
  <C/>
  <D/>
</TOP>

此外,子元素也可能具有需要按新序列预期排序的元素.谢谢!

Also children also might have elements which need to also be sorted into the new sequence expected ordering. Thanks!

推荐答案

您可以以更具声明性的方式使用嵌入在样式表中的查找列表",而不是在模板中指定要排序的所有元素:

Instead of specifying all the elements to order within a template, you may use in a more declarative way a "lookup list" embedded in the stylesheet:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
   xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
   xmlns:my="my-namespace" 
   exclude-result-prefixes="my">
  <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
  <my:Top>
    <my:A>
      <my:AA/>
      <my:AB/>
      <my:AC/>
    </my:A>
    <my:B/>
    <my:C/>
    <my:D/>
  </my:Top>
  <xsl:template match="my:*">
    <xsl:param name="source"/>
    <xsl:variable name="current-lookup-elem" select="current()"/>
    <xsl:for-each select="$source/*[name()=local-name($current-lookup-elem)]">
      <xsl:copy>
        <xsl:apply-templates select="$current-lookup-elem/*">
          <xsl:with-param name="source" select="current()"/>
        </xsl:apply-templates>
        <xsl:copy-of select="text()"/>
      </xsl:copy>
    </xsl:for-each>
  </xsl:template>
  <xsl:template match="/Top">
    <xsl:apply-templates select="document('')/*/my:*">
      <xsl:with-param name="source" select="/"/>
    </xsl:apply-templates>
  </xsl:template>
</xsl:stylesheet>

此示例:

<Top>
  <A>
    <AC/>
    <AA/>
  </A>
  <D/>
  <B/>
  <C>yyy</C>
  <A>
    <AB/>
    <AC/>
    <AA>xxx</AA>
  </A>
</Top>

将返回:

<Top>
    <A>
        <AA>xxx</AA>
        <AC/>
    </A>
    <A>
        <AA/>
        <AB/>
        <AC/>
    </A>
    <B/>
    <C>yyy</C>
    <D/>
</Top>

这篇关于将 XML 转换为指定的顺序 (DTD -> XSD)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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