如何从 XML 中提取重复的 n 个标签之间的行并继续直到最后一个标签?

How to extract lines between repetitive n number of tags from XML and continue until last tag?

我有一个包含超过 2,500 个 <Item> 元素的 XML 文件。

下面的示例显示了示例布局。我想将 <Item name="1st"><Item name="500th"> 之间的每一行按原样复制到一个新文件中。然后继续从 <Item name=501st"> 开始的下一个 500,并将其写入新文件。结果是 5 个新文件。没有什么可以跳过的。

<Item name="1st"><ItemProperties>
<property>data</property><property>data</property>
</ItemProperties>
...
...
<Item name="500th"><ItemProperties>
<property>data</property><property>data</property>
</ItemProperties>

下面的操作只针对前 500 个,但我不知道如何继续操作直到最后一个结束标记。

xmllint --xpath "//Item[position()<=500]" FileName.XML > Output1.XML

请参阅 this link 示例:

import xml.etree.ElementTree as ET
xml_doc = ET.parse('table.xml')
results = xml_doc.getroot()
def chunkify(lst,n):
  # Split the list into 'n' equal parts
  return [ lst[i::n] for i in xrange(n) ]

count = 1
for f in chunkify(results,5):
  temp_str = ''
  for element in f:
    temp_str = temp_str + ET.tostring(element)
  with open(str(count) +"_Output.xml", "w") as text_file:
    text_file.write(temp_str)
  count = count +1

使用python,第一个解决方案是从第0行到最后一行,一次处理一行:

nfh = None
with open('foo.xml') as fh:
    num = 0
    for index, line in enumerate(fh):
        if not index % 500:
            num += 1
            if nfh:
                nfh.close()
            nfh =  open('file_name{}.txt'.format(num), 'w')
        nfh.write(line)
if nfh:
    nfh.close()

其次,使用 lxml 仅枚举 XML 文件中的特定标记:

import lxml.etree as etree
xml_data = etree.parse('foo.xml')
nfh = None
num = 0

for index, tag in enumerate(xml_data.xpath('//Item')):
    # Enumerate 500 tags
    if not index % 500:
        num += 1
        if nfh:
            nfh.close()
        nfh =  open('Output{}.XML'.format(num), 'wb')
    nfh.write(etree.tostring(tag))
if nfh:
    nfh.close()

假设您的 XML 更接近于此:

<root>
<Item name="1st"><ItemProperties>
<property>data</property><property>data</property>
</ItemProperties>
</Item>
<Item name="2nd"><ItemProperties>
<property>data</property><property>data</property>
</ItemProperties>
</Item>
....
<Item name="500th"><ItemProperties>
<property>data</property><property>data</property>
</ItemProperties>
</Item>
....
</root>