【问题标题】:Set leaf node value as an attribute将叶节点值设置为属性
【发布时间】:2013-03-01 06:13:43
【问题描述】:

我有这种类型的 XML 文件(test.xml):

<product>
  <node>
    <region_id>
      <node>1</node>
    </region_id>
    <region_time>
      <node>27</node>
      <node>02</node>
      <node>2013</node>
    </region_time>
    <tab_id>351</tab_id>
    <product_id>1</product_id>
    <tab_name>test1</tab_name>
  </node>
</product>

我想把它们改成这种类型:

<product>
  <region_id>1</region_id>
  <region_time>27,02,2013</region_time>
  <tab_id value="351"></tab_id>
  <product_id value="1"></product_id>
  <tab_name value="test1"></tab_name>
</product>

这里我用的是XSLTPHP

我的 XSLT 代码(test.xsl):

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" 
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:strip-space elements="*"/>

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

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

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

 <!-- from dimitre\'s xsl.thanks -->
 <xsl:template match="node[position()>1]/text()">
   <xsl:text>,</xsl:text>
   <xsl:value-of select="."/>
 </xsl:template>
</xsl:stylesheet>

xslt.php

$sourcedoc = new DOMDocument();
$sourcedoc->load('test.xml');

$stylesheet = new DOMDocument();
$stylesheet->load('test.xsl');

// create a new XSLT processor and load the stylesheet
$xsltprocessor = new XSLTProcessor();
$xsltprocessor->importStylesheet($stylesheet);

// save the new xml file
file_put_contents('test-translated.xml', $xsltprocessor->transformToXML($sourcedoc));

使用此代码 O/P 为:

<product>
  <region_id>1</region_id>
  <region_time>27,02,2013</region_time>
  </tab_id>
  </product_id>
  </tab_name>
</product>

未给出&lt;tab_id&gt; &lt;product_id&gt;&lt;tab_name&gt;

谢谢..

【问题讨论】:

    标签: php xml xslt


    【解决方案1】:

    像这样添加&lt;xsl:template&gt; 元素应该可以解决问题:

    <xsl:template match="tab_id | product_id | tab_name">
      <xsl:copy>
        <xsl:attribute name="value">
          <xsl:value-of select="."/>
        </xsl:attribute>
      </xsl:copy>
    </xsl:template>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 2016-05-04
      • 1970-01-01
      • 1970-01-01
      • 2022-10-03
      • 2012-03-14
      相关资源
      最近更新 更多