将XML解析为带有数组的文件

时间:2019-02-21 12:34:19

标签: python xml parsing elementtree minidom

我需要生成以下文件。使用python解析XML示例:

示例XML

<fruits>
<tag beginTime="20181125020000" endTime="20181202020000">
<EventId>16778</EventId>
    <item color="red">
        <name>apple</name>
        <count>1</count>
        <subtag>
            <Info name="Eid">396</Info>
            <Info name="New">397</Info>
        </subtag>
    </item>
    <item color="yellow">
        <name>banana</name>
        <count>2</count>
        <subtag>
            <Info name="Eid">500</Info>
            <Info name="New">650</Info>
            <Info name="Col">999</Info>
        </subtag>
    </item>
</tag>  

所需的输出:

20181125020000|20181202020000|16778|red|apple|1|Eid;396;New;397|
20181125020000|20181202020000|16778|yelow|banana|1|Eid;500;New;650;Col;999|

2 个答案:

答案 0 :(得分:0)

尝试此代码。

...
correct_predict=tf.equal(tf.argmax(logits,1),tf.argmax(y,1))
accuracy=tf.reduce_mean(tf.cast(correct_predict,tf.float32))
tf.summary.scalar("acc", accuracy)
...
write_op = tf.summary.merge_all()
...
with tf.Session() as sess:
    writer = tf.summary.FileWriter("graph/", sess.graph)
    ...
       if step%10==0:
           summ=sess.run(write_op,feed_dict={x:x_test,y:y_test})
           writer.add_summary(summ,step)
           writer.flush()

答案 1 :(得分:0)

另一种方法是将XML转换为json

import xmltodict

with open('file.xml') as f:
    d = xmltodict.parse(f.read())['fruits']['tag']

for i in d['item']:
    subtag = []
    for s in i['subtag']['Info']:
        subtag.append('{};{}'.format(s['@name'], s['#text']))
    print('{}|{}|{}|{}|{}|{}|{}|'.format(d['@beginTime'], d['@endTime'], d['EventId'], i['@color'], i['name'], i['count'], ';'.join(subtag)))

输出:

20181125020000|20181202020000|16778|red|apple|1|Eid;396;New;397|
20181125020000|20181202020000|16778|yellow|banana|2|Eid;500;New;650;Col;999|