使用XSLT将XML格式转换为另一种XML格式(在输出xml中添加一行)

时间:2014-04-30 05:22:59

标签: xml xslt

我是XSLT和xml的新手,我需要将输入xml更改为输出xml,假设事先几乎不知道输入和输出XML。

输入

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ad:AcceptDataInfo xmlns:ad="http://www.abc.com">
<ad:Product>ABC</ad:Product>
<ad:Filename>test.pdf</ad:Filename>
<ad:AccountNo>123</ad:AccountNo>
<ad:Date>20140429</ad:Date>
<ad:Time>160102</ad:Time>
</ad:AcceptDataInfo>

预期输出

<Documents>
<Document>
<Prop>
  <Name>Product</Name>
  <Value>ABC</Value>
</Prop>
<Prop>
  <Name>Filename</Name>
  <Value>test.pdf</Value>
</Prop>
<Prop>
  <Name>AccountNo</Name>
  <Value>123</Value>
</Prop>
<Prop>
  <Name>Date</Name>
  <Value>20140429</Value>
</Prop>
<Prop>
  <Name>Time</Name>
  <Value>160102</Value>
</Prop>
<File>test.pdf</File>
</Document>
</Documents>

xslt文件

<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="*"/>

<xsl:template match="/*">
    <Documents>
        <Document>
            <xsl:apply-templates select="*"/>
        </Document>
    </Documents>
</xsl:template>

<xsl:template match="*">
    <Prop>
      <Name><xsl:value-of select="local-name()"/></Name>
      <Value><xsl:value-of select="."/></Value>
    </Prop>
</xsl:template>

<xsl:template match=
  "Value[count(.|((//Value)[2])) = 1]">
    <File>
      <xsl:apply-templates />
    </File>
</xsl:template>  

</xsl:stylesheet>
问题是,输出不包括以下行     检验.pdf 从文件名标签

复制文件标签的值

任何帮助将不胜感激,谢谢。

1 个答案:

答案 0 :(得分:1)

嗯,样式表的问题在于您匹配的Value不在输入XML中。

您可以尝试以下样式表:

<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="*"/>

    <xsl:template match="/*">
        <Documents>
            <Document>
                <xsl:apply-templates select="*"/>
                <File><xsl:value-of select="child::*[local-name() = 'Filename']"/></File>
            </Document>
        </Documents>
    </xsl:template>

    <xsl:template match="*">
        <Prop>
            <Name><xsl:value-of select="local-name()"/></Name>
            <Value><xsl:value-of select="."/></Value>
        </Prop>
    </xsl:template>

</xsl:stylesheet>
相关问题