2009-11-13 163 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。这有点复杂,但基本上代码是处理所有元素和子元素。对于每个元素,它将属性分割为需要转换的值和其他值。它复制除了值属性之外的每个元素,每个子元素和每个属性。值属性被处理并给出另一个值。 (但是,如果你想保留它,你也可以只添加原始值。)