Question

To parse an input text file and generate a) an XML file and b) an SVG (also XML) file.

The input text file (input.txt) contains the description of a number of produce distribution centers and storage centers around the country. Each line describes either a single distribution center (dcenter) or a storage center, each with a number of properties; each property name (code for example) is separated by its value with a =.

Example (input.txt)

dcenter: code=d1, loc=San Jose, x=100, y=100, ctype=ct1
dcenter: code=d2, loc=San Ramon, x=300, y=200, ctype=ct2
storage: code=s1, locFrom=d1, x=50, y=50, rtype=rt1
storage: code=s2, locFrom=d1, x=-50,y=100, rtype=rt1

The desired Output of the program:

Output 1

<?xml version="1.0"?>
<dcenters>
<dcenter code="d1">
<loc> San Jose </loc>
<x> 100 </x>
<y> 100 </y>
<ctype> ct1 </ctype>
</dcenter>
<storage code="S1">
<locFrom> d1 </locFrom>
<x> 150 </x>
<y> 150 </y>
<rtype> rt1 </rtype>
</storage>
<storage code="S2">
<locFrom> d1 </locFrom>
<x> 50 </x>
<y> 200 </y>
<rtype> rt1 </rtype>
</storage>

Please help me with the program. I will really appreciate.

Was it helpful?

Solution

Suppose the input is in string s; either from direct assignment or from file.read:

s="""dcenter: code=d1, loc=San Jose, x=100, y=100, ctype=ct1
dcenter: code=d2, loc=San Ramon, x=300, y=200, ctype=ct2
storage: code=s1, locFrom=d1, x=50, y=50, rtype=rt1
storage: code=s2, locFrom=d1, x=-50,y=100, rtype=rt1"""

Then you can this:

print '<?xml version="1.0"?>'
print "<dcenters>"
for line in s.splitlines():
    type, fields = line.split(":")
    params = fields.split(",")
    code = params[0].split("=")[1].strip()
    print '<%s code="%s">' % (type, code)
    for p in params[1:]:
        ptype, pvalue = p.strip().split("=")
        print '<%s> %s </%s>' % (ptype, pvalue, ptype)
    print '</%s>' % type
print "</dcenters>"

Not sure why d2 is missing from your sample output; I assume that's by mistake.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top