2009-11-13 161 views
0

我有很多與數據文件轉換爲使用基本的數學函數百分比:負整數百分比

<param id="1" name="otb" value="0.160"/> 
<param id="2" name="blm" value="-0.210"/> 
<param id="3" name="mep" value="-0.010"/> 
<param id="4" name="plc" value="-0.100"/> 

每個ID得到的它自己的公式:

  1. (N - ( - 。 3))/ 2.3 * 100
  2. (N - ( - 8))/ 3.3 * 100
  3. (N - ( - 5))/ 1.5 * 100
  4. (N - (1)) /1.1*100

所以我得到:

OTB = 8 BLM = 20 MEP = 24 PLC = 0

什麼是通過正則表達式...和PHP運行所有這些文件的好方法?那裏有任何快速和髒的代碼? :D

+0

我想我們需要知道「這些文件」是什麼樣的建議RegExes。 – Franz 2009-11-13 10:32:35

+0

家庭作業,還是真正的挑戰? – 2009-11-13 10:34:59

+0

只好包裝在代碼標籤中。固定。 – 2009-11-13 10:36:04

回答

1

由於該文件似乎是XML格式,我建議您嘗試PHP simplexml庫。該文檔可以找到here

然後,您可以簡單地通過訪問XML對象的魔法屬性訪問XML樹:

$xml = simplexml_load_file('your/path/to/your/file'); 

foreach ($xml->param as $param) 
{ 
    $id = $param['id']; 
    $name = $param['name']; 
    $value = $param['value']; 

    // do your calculations... 
} 
+0

或者使用XML樣式表進行簡單的轉換。 :-) – 2009-11-13 10:44:52

+0

@Bravo Charly:這是否工作? – Franz 2009-11-13 11:06:35

+0

@Franz:目前看起來不錯...仍在閱讀文檔。我絕不是編碼員,哈。 – 2009-11-13 11:11:52

0

樣式魔術:

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format"> 
    <xsl:output indent="yes" standalone="yes" omit-xml-declaration="yes" method="xml"/> 
    <xsl:template match="*"> 
    <xsl:copy> 
     <xsl:variable name="Values" select="@*[(name(..)='param') and ((name(.)='value'))]"/> 
     <xsl:variable name="NonValues" select="@*[. != $Values]"/> 
     <xsl:apply-templates select="$NonValues" mode="NonValues"/> 
     <xsl:apply-templates select="$Values" mode="Values"/> 
     <xsl:choose> 
     <xsl:when test="*"> 
      <xsl:apply-templates select="*"/> 
     </xsl:when> 
     <xsl:otherwise> 
      <xsl:value-of select="."/> 
     </xsl:otherwise> 
     </xsl:choose> 
    </xsl:copy> 
    </xsl:template> 
    <xsl:template match="@*" mode="Values"> 
    <xsl:attribute name="value"><xsl:variable name="n" select="."/><xsl:choose><xsl:when test="../@id=1"><xsl:value-of select="(($n - (-0.3)) div 2.3) * 100"/></xsl:when><xsl:when test="../@id=2"><xsl:value-of select="(($n - (-0.8)) div 3.3) * 100"/></xsl:when><xsl:when test="../@id=3"><xsl:value-of select="(($n - (-0.5)) div 1.5) * 100"/></xsl:when><xsl:when test="../@id=4"><xsl:value-of select="(($n - (0.1)) div 1.1) * 100"/></xsl:when><xsl:otherwise><xsl:value-of select="."/></xsl:otherwise></xsl:choose></xsl:attribute> 
    </xsl:template> 
    <xsl:template match="@*" mode="NonValues"> 
    <xsl:copy> 
     <xsl:value-of select="(.)*2"/>pp 
    </xsl:copy> 
    </xsl:template> 
</xsl:stylesheet> 

如果你可以用這個樣式錶轉換的原始XML,您將得到一個帶有計算結果的新XML。這有點複雜,但基本上代碼是處理所有元素和子元素。對於每個元素,它將屬性分割爲需要轉換的值和其他值。它複製除了值屬性之外的每個元素,每個子元素和每個屬性。值屬性被處理並給出另一個值。 (但是,如果你想保留它,你也可以只添加原始值。)