2012-03-28 44 views
1

給定兩種xml格式的常見做法是什麼?你將如何將第一種格式轉換爲第二種格式,正則表達式?我應該有<subgroupones>嗎?除<global>之外,基本上任何<tags>都應該被刪除,或者如果有更優雅的方式。xml常見做法和刪除組

<global> 
    <groupone name="bce"> 
     <subgroupones> 
      <subsgroupone name="a" /> 
      <subsgroupone name="b" /> 
      <subsgroupone name="c" /> 
     </subgroupones> 
    <groupone> 
</global> 

<global> 
    <groupone name="bce"> 
      <subsgroupone name="a" /> 
      <subsgroupone name="b" /> 
      <subsgroupone name="c" /> 
    <groupone> 
</global> 

回答

2

XML到XML的轉換幾乎總是通過樣式錶轉換(XSLT)最好地處理。 PHP已經內置了用於處理XSLT庫:http://php.net/manual/en/book.xslt.php

例如,這裏是一個將僅複製具有屬性(與<global>除外,它總是包含)元素的XSLT:

<?xml version="1.0"?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:template match="global | @* | node()[@*]"> 
    <xsl:copy><xsl:apply-templates select="@* | node()"/></xsl:copy> 
    </xsl:template> 
</xsl:stylesheet> 

樣本輸出(目前還不能確定如何刪除多餘的空間):

<?xml version="1.0" encoding="UTF-8"?><global> 
    <groupone name="bce"> 

      <subsgroupone name="a"/> 
      <subsgroupone name="b"/> 
      <subsgroupone name="c"/> 

    </groupone> 
</global> 

你可以用這個工具實驗:http://xslttest.appspot.com/