簡體   English   中英

使用 xml.etree.ElementTree 獲取 XML 行

[英]Get XML Line with xml.etree.ElementTree

我正在搜索一個函數,其中參數是一個整數(行),返回值將 xml-Line 提供給該整數。

我有一個很大的 XMl 文件,我想將它減少到一些較小的文件中。 每個輸出文件都有一個開始標簽和結束標簽

例如

輸入文件。:Test.xml

輸出文件:

Test1.xml Test2.xml Test3.xml Test4.xml

tree = etree.parse(file_name)
root = tree.getroot()

# Here i count the number of XMl Lines in my file
xml_lines = 0

for child in root:
    xml_lines +=1

# Here i want to get the String of my XMl Line by giving the number
for i in range(counter,counter+number_of_each_file):
            d.write(FUNCTION)

我認為您應該改變將大 XML 文件拆分為較小 XML 文件的方法。 XML 不關心行。 它關心元素。 您的函數應該獲取大 XML 的根目錄、dest_file_name_prefix 和一個代表每個小 XML 文件中所需元素的數字。

就像是:

def split_xml(root,dest_file_name_prefix,num_of_elements):
    """ Loop around the elements under to root and save a each collection of 'num_of_elements' to a file  having a unique  name """
    root = tree.getroot()
    elements = root.findall('.//element')
    counter = 0 
    temp = []
    for idx,element in enumerate(elements)
        temp.append(element)
        if idx > 0 and idx % num_of_elements == 0:
            # save the elements to a 'small' file
            counter += 1
            file_name = '{}_{}'.format(dest_file_name_prefix,counter)
            #TODO I assume you know how to save the elements from temp to a file  
            temp = []

大 XML 示例

<root>
   <element id="0"></element>
   <element id="1"></element>
   <element id="2"></element>
   ...
   <element id="10000"></element>
</root>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM