我在用python创建xml文件时遇到了问题。我的脚本在开始时加载了一个文本文件,读取每一行并检查内容是否包含特定的字符串,根据它我想要在xml文件中创建一个标记或。为此,我使用了ElementTree
模块。
这是代码
for line in myfile.read().splitlines():
if 'EXTINF' in line:
root = etree.Element("item")
etree.SubElement(root, "title").text = line
elif 'http' in line:
etree.SubElement(root, "link").text = 'http:\\mysite.com\'
tree = etree.ElementTree(root)
tree.write('my\\path\\'+xml_file.xml)
xml文件只包含for循环迭代的最后一个元素。
我想要的输出是:
<item>
<title> "my title" </title>
<link> "http:\\mysite.com" </link>
</item>
<item>
<title> "my title" </title>
<link> "http:\\mysite.com" </link>
</item>
<item>
<title> "my title" </title>
<link> "http:\\mysite.com" </link>
</item>
怎么了?谢谢
发布于 2018-06-17 02:56:38
每次找到'EXTINF'
时,您都会替换指定为root
变量的元素。
for line in myfile.read().splitlines():
if 'EXTINF' in line:
root = etree.Element("item") ## Creates a New Element called "item" with a variable name of "root"
etree.SubElement(root, "title").text = line ## Creates a subelement called "title" to the current root variable
elif 'http' in line:
etree.SubElement(root, "link").text = 'http:\\mysite.com\' ## Creates a subelement called "title" to the current root variable
tree = etree.ElementTree(root) ## Create an ElementTree Object using the current root variable
tree.write('my\\path\\'+xml_file.xml)
因此,很明显,您需要确定root
变量应该是什么( XML树中最低的节点),然后使用不同的变量来创建root
的SubElements。此外,根据您的原始代码和所需的输出,我假设只输出带有标题的项,因此您的代码需要反映这一点(具体地说,在您的代码中,只有在行中有'EXTINF‘的情况下才创建item
元素,并且您的示例输出中没有一个缺少标题)。
root = etree.Element("root")
for line in myfile.read().splitlines():
if 'EXTINF' in line: ## If it has a title, then create an item.
subelement = etree.SubElement(root,"item")
etree.SubElement(subelement, "title").text = line
if 'http' in line: ## Check if it has a link
etree.SubElement(subelement, "link").text = 'http:\\mysite.com\'
tree = etree.ElementTree(root)
如果你对没有标题的项目没意见:
for line in myfile.read().splitlines():
subelement = etree.SubElement(root,"item") ## Always Create an item for each line
if 'EXTINF' in line:
etree.SubElement(subelement, "title").text = line
if 'http' in line:
etree.SubElement(subelement, "link").text = 'http:\\mysite.com\'
EDIT:另外,您是否考虑过使用myfile.readlines()
而不是myfile.read().splitlines()
https://stackoverflow.com/questions/50873711
复制相似问题