pythonlxml以预定义的ord写入文件

2024-09-30 12:27:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我想写下面的lxml etree子元素:

<ElementProtocolat0x3803048>,
<ElementStudyEventDefat0x3803108>,
<ElementFormDefat0x3803248>,
<ElementItemGroupDefat0x38032c8>,
<ElementClinicalDataat0x3803408>,
<ElementItemGroupDataat0x38035c8>,
<ElementFormDefat0x38036c8>,

预定义的顺序将其转换为odm xml文件。i、 e

^{pr2}$

是否有任何方法可以对元素进行排序,即使用预定义的列表?在

predefined_order = ['Protocol', 'StudyEventDef','FormDef','ItemGroupDef','ItemDef','CodeList']

Tags: 文件元素顺序xmllxmletreeodmpr2
2条回答

此示例演示:

  • 如何读入XMl文件
  • 元素是一个列表,并且可以这样操作
  • 如何根据可匹配子字符串的预定义顺序对列表排序
  • 如何写出XML文件
from lxml import etree
import re

# Parse the XML and find the root
with open('input.xml') as input_file:
    tree = etree.parse(input_file)
root = tree.getroot()

# Find the list to sort and sort it
some_arbitrary_expression_to_find_the_list = '.'
element_list = tree.xpath(some_arbitrary_expression_to_find_the_list)[0]

predefined_order = [
    'Protocol',
    'StudyEventDef',
    'FormDef',
    'ItemGroupDef',
    'ItemGroupData',
    'ItemDef',
    'CodeList',
    'ClinicalData']
filter = re.compile(r'Element(.*)at0x.*')

element_list[:] = sorted(
    element_list[:],
    key = lambda x: predefined_order.index(filter.match(x.tag).group(1)))

# Write the XML to the output file
with open('output.xml', 'w') as output_file:
    output_file.write(etree.tostring(tree, pretty_print = True))

样本输入: 在

^{pr2}$

输出: 在

<stuff>
<ElementProtocolat0x3803048/>
<ElementStudyEventDefat0x3803108/>
<ElementFormDefat0x3803248/>
<ElementFormDefat0x38036c8/>
<ElementItemGroupDefat0x38032c8>Random Text</ElementItemGroupDefat0x38032c8>
<ElementItemGroupDataat0x38035c8><tag1><tag2 attr="random tags"/></tag1></ElementItemGroupDataat0x38035c8>
<ElementClinicalDataat0x3803408/>
</stuff>

很抱歉,我缺乏xml方面的知识,但我试图仅使用Python的基本知识按排序顺序格式化数据。在

import re
data = """<ElementProtocolat0x3803048>,
<ElementStudyEventDefat0x3803108>,
<ElementFormDefat0x3803248>,
<ElementItemGroupDefat0x38032c8>,
<ElementClinicalDataat0x3803408>,
<ElementItemGroupDataat0x38035c8>,
<ElementFormDefat0x38036c8>,"""

predefined_order = ['Protocol','StudyEventDef','FormDef','ItemGroupDef','ItemGroupData','CodeList', 'ClinicalData']

fh1 = open("something.xml","w")
for i in predefined_order:
    for j in data.split(','):
        if re.search(i,j):
            fh1.write(j + ',')

输出:

^{pr2}$

相关问题 更多 >

    热门问题