如何用Java DOM Parser参照另一XML文件重排XML标签顺序
按参照XML的结构重新排列source.xml的标签顺序
我有一个XML文件source.xml,内容如下:
<students> <student2> <college>SIET</college> <name>Rithvik</name> </student2> <student1> <college>SCET</college> <name>Prabhas</name> </student1> </students>
另有一个参照XML文件referenced.xml,内容如下:
<students> <student1> <name>Prabhas</name> <college>SCET</college> </student1> <student2> <name>Ritvik</name> <college>SIET</college> </student2> </students>
我的需求是参照referenced.xml的标签顺序(包括同级元素的排列顺序,以及每个元素内部子标签的顺序),重新排列source.xml的标签,最终让source.xml的结构与referenced.xml完全一致,预期输出如下:
<students> <student1> <name>Prabhas</name> <college>SCET</college> </student1> <student2> <name>Ritvik</name> <college>SIET</college> </student2> </students>
尝试了多种方法都没解决,求帮助。
解决方案:使用XSLT实现结构对齐
可以编写XSLT样式表,读取参照XML的结构顺序,然后按照这个顺序重新组织source.xml的内容。以下是完整的XSLT代码:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <!-- 引入参照XML文档 --> <xsl:param name="ref-doc" select="document('referenced.xml')"/> <!-- 匹配所有节点,默认复制 --> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> <!-- 匹配元素节点,按照参照文档的顺序重新排列子元素 --> <xsl:template match="*"> <xsl:copy> <xsl:apply-templates select="@*"/> <!-- 遍历参照文档中当前元素的子元素顺序 --> <xsl:for-each select="$ref-doc//*[name() = name(current())]/*"> <!-- 从source中选取对应名称的子元素 --> <xsl:apply-templates select="current()/*[name() = name(current())]"/> </xsl:for-each> </xsl:copy> </xsl:template> <!-- 匹配根节点,按照参照文档的顺序排列顶层子元素 --> <xsl:template match="/"> <xsl:apply-templates select="$ref-doc/*"> <xsl:with-param name="source-root" select="/*"/> </xsl:apply-templates> </xsl:template> <xsl:template match="/*"> <xsl:param name="source-root"/> <xsl:copy> <xsl:apply-templates select="@*"/> <!-- 按参照文档的顺序排列子元素 --> <xsl:for-each select="*"> <xsl:apply-templates select="$source-root/*[name() = name(current())]"/> </xsl:for-each> </xsl:copy> </xsl:template> </xsl:stylesheet>
使用方法
- 将上述XSLT代码保存为
reorder.xsl - 使用XSLT处理器(比如
xsltproc,大多数Linux系统自带,Windows可下载相关工具)执行命令:xsltproc --stringparam ref-doc referenced.xml reorder.xsl source.xml > output.xml - 生成的
output.xml就是符合要求的结果,可将其重命名为source.xml覆盖原文件。
说明
- 该XSLT会严格按照
referenced.xml的元素层级顺序排列source.xml内容,包括顶层student1/student2的顺序,以及每个student内部name/college的顺序。 - 仅处理两个文件共有的元素:
source.xml中存在但参照文档没有的元素会被忽略;参照文档中有但source.xml没有的元素不会新增。
内容的提问来源于stack exchange,提问作者Yogendra
相关产品推荐
相关产品推荐

