Afnan
Afnan

Reputation: 89

Write one tag with its content of xml file into other xml file python

I have huge xml file with many tags. I need to extract one content of one tag and write it into other xml file using python code. The below are a sample of xml code:

<madamira_output xmlns="urn:edu.columbia.ccls.madamira.configuration:0.1">
     <out_seg id="SENT1">
           <word1>.....</word1>
           <word2>.....</word2>
     </out_seg>
     <out_seg id="SENT2">
           <word1>.....</word1>
           <word2>.....</word2>
     </out_seg>

And the below is python code:

 from xml.etree import ElementTree
 with open('100.xml', 'rt') as f:
     tree = ElementTree.parse(f)
 sent=[]
 for node in tree.iter('{urn:edu.columbia.ccls.madamira.configuration:0.1}out_seg'):
     sent.append(node)
 count_file=1
 for i in sent:
     save_path = '/Desktop/13/out'
     completeName = os.path.join(save_path, str(count_file)+".xml")
     count_file=count_file+1
     with open(completeName, "w") as f:
         f.write(i)

But nothing is written in files. Please help

Upvotes: 3

Views: 66

Answers (1)

tan
tan

Reputation: 51

subelements format of out_seg is incorrect. the end tag (word1) doesn't match the start tag(word_1).

second, using following code to write a element content into a file:

with open(completeName, "w") as f:

     f.write(ElementTree.tostring(i))

Upvotes: 1

Related Questions