简体   繁体   中英

How can I re-create this XML code using python etree?

While I was doing research on how to use xml.etree.ElementTree, all videos that I've seen show how to output HTML like so: <drawing> then the contents in between and then closing </drawing> ie like normal HTML. The xml though that I'm trying to emulate has something like this:

<Drawings>  
<Drawing  
SHOWRIDE_FLAG="FACILITY"  
DOCUMENT_TYPE="Facility Image"  
FILE_NAME="DE-103.5_R3.pdf"  
FILE_PATH="H:\EDMS\EXAMPLE"  
FILE_TYPE="PDF"  
DOCUMENT_NUMBER="DE-103.5"  
REVISION="03.00"  
DOC_TITLE="SHOW EQUIPMENT POWER - ROOF"  
PAGE_COUNT="1"  
DRAWING_SIZE="E"  
DISCIPLINE="ELECTRICAL, SHOW"  
PART_NUMBER=""  
COMPONENT="DRAWING"  
COMMENTS=""  
>
</Drawing>  
</Drawings>  

If you notice, that after <Drawing it goes right into SHOWRIDE_FLAG . The closing for this doesn't happen until all the way until the end right after comments. Basically what I'm trying to make is a program that looks at a CSV file, locates the drawing number, name, revision, etc, and then connects that to a PDF so that I can generate an XML file and place it into our EDMS system. I figured I'd start at the back as that would be the most difficult and if I can't generate a simple XML, it would be a waste to try everything from the beginning as I know I can do that easily. Right now, we use a program that someone created a long time ago, but in that program I have to add in all the title text, revision, drawing numbers, which is if for a few drawings but when you have over 300 to do, it can be quite a pain.

This is my code so far as I figured I'd start out easy:

import xml.etree.ElementTree as ET

#create the file structure

drawings = ET.Element('Drawings')

drawing = ET.Element(drawings, 'drawing', drawingCOMMENTS = 'Drawing COMMENTS', component = 'COMPONENT')



#create a new xml file with results

tree = ET.ElementTree(drawings)
tree.write('example_text.xml')

But this generates code that looks like this:

<Drawings><Drawing COMMENTS ="" /><COMPONENT ="DRAWING" /></Drawings>

Any ideas?

# create "Drawings" element
drawings = ET.Element('Drawings')

# attributes are supplied as a dict
drawing = ET.Element('drawing', {'COMMENTS': 'Drawing COMMENTS', 'component': 'COMPONENT'})

# append child element to parent
drawings.append(drawing)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM