python - How to build an xml template with variable attributes from scratch -
my goal build xml template placeholders variable attributes. reasons, template not take in new data placeholders.
here's example:
x=2*5 xmltemplate=""" <personal reference="500.txt">     <others:sequence>         <feature:name="name" age="age" dob="dob"/>     </others:sequence> </personal>""".format(name='michael', age=x, dob=15/10/1900) print xmltemplate   output:
<personal reference="500.txt">     <others:sequence>         <feature:name="name" age="age" dob="dob"/>     </others:sequence> </personal>   ideal output:
<personal reference="500.txt">     <others:sequence>         <feature:name="michael" age="10" dob="15/10/1900"/>     </others:sequence> </personal>   any ideas? thanks.
your template needs curly braces:
x=2*5 xmltemplate=""" <personal reference="500.txt">     <others:sequence>         <feature:name="{name}" age="{age}" dob="{dob}"/>     </others:sequence> </personal>""".format(name='michael', age=x, dob='15/10/1900') print xmltemplate   yields
<personal reference="500.txt">     <others:sequence>         <feature:name="michael" age="10" dob="15/10/1900"/>     </others:sequence> </personal>   the format method replaces names in curly-braces. compare, example,
in [20]: 'cheese'.format(cheese='roquefort') out[20]: 'cheese'  in [21]: '{cheese}'.format(cheese='roquefort') out[21]: 'roquefort'   i see have lxml. excellent. in case, use lxml.builder construct xml. create valid xml:
import lxml.etree et import lxml.builder builder e = builder.e f = builder.elementmaker(namespace='http://foo', nsmap={'others':'http://foo'})  x = 2*5 xmltemplate = et.tostring(f.root(     e.personal(         f.sequence(             e.feature(name='michael',                    age=str(x),                    dob='15/10/1900')             ), reference="500.txt")),                           pretty_print=true) print(xmltemplate)   yields
<others:root xmlns:other="http://foo">   <personal reference="500.txt">     <others:sequence>       <feature dob="15/10/1900" age="10" name="michael"/>     </others:sequence>   </personal> </others:root>   and string can parsed lxml using:
doc = et.fromstring(xmltemplate) print(doc) # <element {http://foo}root @ 0xb741866c>      
Comments
Post a Comment