[英]Transforming a XML document into another XML schema
I want to transform an XML document with a specific schema into another XML document, giving it a specific different schema. 我想将具有特定模式的XML文档转换为另一个XML文档,为其提供特定的不同模式。
To give an example, the input could be as follows: 举个例子,输入可以如下:
<?xml version="1.0" encoding="UTF-8"?>
<Abcd field1="0" field2="3" field3="1" field4="_sometext" field5="text" field6="Helloworld" />
<Efgh _id="2790" size="2">
<i>2771</i>
<i>2781</i>
</Efgh>
The corresponding output for this example is: 此示例的相应输出是:
<?xml version="1.0" encoding="UTF-8"?>
<field name="Abcd"> field1="0" field2="3" field3="1" field4="_sometext" field5="text" field6="Helloworld" </field>
<field name="Efgh"> _id="2790" size="2"
<i>2771</i>
<i>2781</i>
</field>
There are only two types of tags: 标签只有两种类型:
I am not sure how to attempt such a transformation (Regex? XSLT?). 我不知道如何尝试这样的转换(Regex?XSLT?)。
If there would be only tags of form 1 (like Abcd), using sed in bash could do the work I think, but with tags of form 2, I do not know how to proceed. 如果只有表单1的标签(如Abcd),在bash中使用sed可以完成我认为的工作,但是使用表单2的标签,我不知道如何继续。
Edit: I wrote a small pipeline using sed that transforms lines of form 1 into the correct counterpart, it works as follows: 编辑:我使用sed写了一个小管道,它将表单1的行转换为正确的对应物,它的工作原理如下:
cat input1.xml | sed "s/ * /\"> /" | sed "s/</<field name=\"/" | sed "s,/>,</field>,"
But how to continue? 但是如何继续?
I am going to take a guess here; 我想在这里猜一下; given the following example input: 给出以下示例输入:
XML XML
<root>
<Abcd field1="0" field2="3" field3="1" field4="_sometext" field5="text" field6="Helloworld" />
<Efgh _id="2790" size="2">
<i>2771</i>
<i>2781</i>
</Efgh>
</root>
the following stylesheet: 以下样式表:
XSLT 1.0 XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<!-- identity transform -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="root/*">
<field name="{local-name()}">
<xsl:apply-templates select="@*|node()"/>
</field>
</xsl:template>
</xsl:stylesheet>
will result in: 将导致:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<field name="Abcd" field1="0" field2="3" field3="1" field4="_sometext" field5="text" field6="Helloworld"/>
<field name="Efgh" _id="2790" size="2">
<i>2771</i>
<i>2781</i>
</field>
</root>
which to me seems much more likely to be the required output. 对我来说似乎更有可能是所需的输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.