Copy XML file contents except for root node and attribute XSLT

杀马特。学长 韩版系。学妹 提交于 2020-01-02 07:34:11

问题


I am working on a small XSLT file to copy the contents of an XML file and strip out the declaration and root node. The root node has an namespace attribute.

I currently have it working except for now the namespace attribute is now being copied to the direct children nodes.

Here is my xslt file so far, nothing big or complicated:

    <?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" omit-xml-declaration="yes" encoding="utf-8"/>
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="/*">
    <xsl:apply-templates select="node()" />
  </xsl:template>
</xsl:stylesheet>

My input file is like this:

<?xml version="1.0" encoding="UTF-8"?>
<Report_Data xmlns="examplenamespace">
    <Report_Entry>
        <Report_Date>
        </Report_Date>
    </Report_Entry>
    <Report_Entry>
        <Report_Date>
        </Report_Date>
    </Report_Entry>
    <Report_Entry>
        <Report_Date>
        </Report_Date>
    </Report_Entry>
</Report_Data>

The output after the XSLT is like this:

<Report_Entry xmlns="examplenamespace">
    <Report_Date>
    </Report_Date>
</Report_Entry>
<Report_Entry xmlns="examplenamespace">
    <Report_Date>
    </Report_Date>
</Report_Entry>
<Report_Entry xmlns="examplenamespace">
    <Report_Date>
    </Report_Date>
</Report_Entry>

The problem is, every Report_Entry tag is now getting that xml namespace attribute from the root node that I removed.

In case you were wondering, I know the output of the XSLT is not well formed. I am adding the XML declaration and a different root node name later on after the XSLT trasnformation.


回答1:


The following produces the output that you want:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:output method="xml" omit-xml-declaration="yes" encoding="utf-8"/>

  <!-- For each element, create a new element with the same local-name (no namespace) -->
  <xsl:template match="*">
    <xsl:element name="{local-name()}">
      <xsl:copy-of select="@*"/> 
      <xsl:apply-templates/>
    </xsl:element>
  </xsl:template>

  <!-- Skip the root element, just process its children. -->
  <xsl:template match="/*">
    <xsl:apply-templates/>
  </xsl:template>

</xsl:stylesheet>


来源:https://stackoverflow.com/questions/19733948/copy-xml-file-contents-except-for-root-node-and-attribute-xslt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!