删除父节点而不影响子节点

时间:2019-11-26 09:13:05

标签: xslt-1.0

我得到的XML输出不是我要求的格式,所以尝试了一些代码来更改格式,但是无法

这是我得到的输出

<?xml version="1.0" encoding="UTF-8"?>
<Envelope xmlns="http://schemas.microsoft.com/dynamics/2011/01/documents/Message">
<Header>
<MessageId>{A124-B421-C325-D467}</MessageId>
<Action>find</Action> 
</Header>
  <Body>
    <MessageParts xmlns="http://schemas.microsoft.com/dynamics/2011/01/documents/Message">
      <Run xmlns="http://schemas.microsoft.com/dynamics/2008/01/documents/Run">

        <RunObject class="entity">
          <A1>NA</A1>
          <A2>False</A2>
          <A3>02</A3>
          <A4>ER</A4>
        </RunObject>

        <RunObject class="entity">
          <A1>NA</A1>
          <A2>False</A2>
          <A3>03</A3>
          <A4>ER</A4>
        </RunObject>

      </Run>
    </MessageParts>
  </Body>
</Envelope>

这是我需要的XML输出

<?xml version="1.0" encoding="UTF-8"?>
<Document>

      <Item>
        <A3>NA</A3>
        <A4>False</A4>
        <A2>02</A2>
        <A1>ER</A1>
      </Item>

      <Item>
        <A3>NA</A3>
        <A4>False</A4>
        <A2>03</A2>
        <A1>ER</A1>
      </Item>

</Document>

这是我用来更改所获取的xml格式的代码

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:m="http://schemas.microsoft.com/dynamics/2011/01/documents/Message"
xmlns:r="http://schemas.microsoft.com/dynamics/2008/01/documents/Run"
exclude-result-prefixes="m r">
  <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
  <xsl:strip-space elements="*"/>
<!-- move all elements to no namespace -->
<xsl:template match="*">
    <xsl:element name="{local-name()}">
      <xsl:copy-of select="@*"/>
      <xsl:apply-templates/>
    </xsl:element>
  </xsl:template>

  <xsl:template match="m:Envelope"/>
  <xsl:template match="m:Header"/>
  <xsl:template match="m:MessageId"/>
  <xsl:template match="m:Action"/>
  <xsl:template match="m:Body"/>

  <!-- rename MessageParts to Document + skip the Run wrapper -->
  <xsl:template match="m:MessageParts">
    <Document>
      <xsl:apply-templates select="r:Run/*"/>
    </Document>
  </xsl:template>
  <!-- rename RunObject to Item + reorder child nodes -->
  <xsl:template match="r:RunObject[@class='entity']">
    <Item>
      <xsl:apply-templates select="r:A3" />
      <xsl:apply-templates select="r:A4" />
      <xsl:apply-templates select="r:A2" />
      <xsl:apply-templates select="r:A1" />
    </Item>
  </xsl:template>
</xsl:stylesheet>

我尝试了上面的代码,但无法更改xml的格式

1 个答案:

答案 0 :(得分:0)

代替:

 <xsl:template match="m:Envelope"/>

将删除Envelope节点及其所有后代,您只需删除Envelope包装器并继续处理其内容:

<xsl:template match="m:Envelope">
    <xsl:apply-templates/>
</xsl:template>

其他包装也一样。实际上,您可以替换所有这些:

  <xsl:template match="m:Envelope"/>
  <xsl:template match="m:Header"/>
  <xsl:template match="m:MessageId"/>
  <xsl:template match="m:Action"/>
  <xsl:template match="m:Body"/>

具有:

<xsl:template match="m:*">
     <xsl:apply-templates select="*"/>
</xsl:template>
相关问题