246 10 Transforming with Traditional Programming Languages
print("<HealthStudy>\n");
while (<>) {
$month = substr($_, 0, 2) + 0;
$day = substr($_, 2, 2) + 0;
$yr = substr($_, 4, 2) + 0;
$year = 1900 + $yr;
$year = 2000 + $yr if $yr < 20;
$bmi = substr($_, 6, 8) + 0;
$status = "normal";
$status = "obese" if substr($_, 14, 3) + 0 > 0;
$status = "overweight" if substr($_, 17, 3) + 0 > 0;
$height = substr($_, 20, 3) + 0;
$weight = substr($_, 23, 8) + 0;
print("<Interview Date=’$year-$month-$day’");
print(" BMI=’$bmi’ Status=’$status’");
print(" Height=’$height’ Weight=’$weight’/>\n");
}
print("</HealthStudy>\n");
Program 10.18 Converting flat file information to XML attributes
011500 18.66 0 0 62 46.27102
011500 26.93 0 1 63 68.95152
020100 33.95 1 0 65 92.53204
020100 17.38 0 0 67 50.35111
The task is to convert this file to an XML document like this:
<HealthStudy>
<Interview Date=’2000-1-15’ BMI=’18.66’ .../>
<Interview Date=’2000-1-15’ BMI=’26.93’ .../>
<Interview Date=’2000-2-1’ BMI=’33.95’ .../>
<Interview Date=’2000-2-1’ BMI=’17.38’ .../>
</HealthStudy>
The solution is shown in program 10.18. This program stores all information
in XML attributes. Another way to store information is to use XML content
instead. For the health study example, the XML document would then look
like this: