python lxml 树,line[] 创建多行,希望单行输出

python lxml tree, line[] creating multiple lines, desire single line output

我正在用 python 使用 lxml 创建一个 xml 文件。我正在逐行解析一个文件,寻找一个字符串,如果该字符串存在,我将创建一个 SubElement。我正在为 SubElement 分配一个值,该值存在于我正在搜索的字符串之后的已解析文件中。

问题:如何将所有 xml 输出到 output.xml 文件中的一行?使用 line[12:] 似乎是问题所在。请参阅下面的详细信息。

每行示例文件内容:

[testclass] unique_value_horse
[testclass] unique_value_cat
[testclass] unique_value_bird

Python代码:

当我硬编码如下所示的字符串时,输出 xml 是 xml 树的一条连续线。完美的!见下文。

with open(file) as openfile:
    for line in openfile:
        if "[testclass]" in line:
            tagxyz = etree.SubElement(subroot, "tagxyz")
            tagxyz.text = "hardcodevalue"

当我尝试将第 13 个字符向前分配为值时,我在输出 xml per SubElement 中得到了一个新行。这会导致输出 xml 文件的接收者出错。见下文。

with open(file) as openfile:
    for line in openfile:
        if "[testclass]" in line:
            tagxyz = etree.SubElement(subroot, "tagxyz")
            tagxyz.text = line[12:]

我认为在同一行上进行赋值可能会有所帮助,但这似乎并不重要。见下文。

with open(file) as openfile:
    for line in openfile:
        if "[testclass]" in line:
            etree.SubElement(subroot, "tagxyz").text = line[12:]

我尝试使用 etree.XMLParser(remove_blank_text=True),并在事后解析输出 xml 文件并重新创建文件,但这似乎没有帮助。我知道这应该有所帮助,但要么我用错了,要么它实际上并不能解决我的问题。见下文。

with open("output.xml", 'w') as f:
    f.write(etree.tostring(project))

parser = etree.XMLParser(remove_blank_text=True)
tree = etree.parse("output.xml", parser)

with open("output2.xml", 'w') as fl:
    fl.write(etree.tostring(tree))

您的行包含行分隔符 \n。您可以使用 str.rstrip():

删除该行
with open(file) as openfile:
    for line in openfile:
        if "[testclass]" in line:
            etree.SubElement(subroot, "tagxyz").text = line.rstrip('\n')

以后使用repr() function调试此类问题;您会很容易地看到由其 Python 转义序列表示的换行符:

>>> line = '[testclass] unique_value_horse\n'
>>> print(line)
[testclass] unique_value_horse

>>> print(repr(line))
'[testclass] unique_value_horse\n'
>>> print(repr(line.rstrip('\n')))
'[testclass] unique_value_horse'