2015-03-02 41 views
0

我正在用python使用lxml创建一个xml文件。我通过逐行解析文件,寻找一个字符串,如果该字符串存在,我创建一个SubElement。我正在分配一个SubElement值,它存在于我搜索的字符串后面的解析文件中。python lxml树,行[]创建多行,渴望单行输出

问题:如何将所有xml输出都放到output.xml文件中的一行上?使用行[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个字符,我得到的每SubElement输出XML新行。这导致输出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)) 

回答

2

您的行包括行分隔符\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' 
+0

完美!这么简单...所有的区别。 – MikeKindaNos 2015-03-02 19:50:47