2015-03-02 43 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