2016-02-19 49 views
2

我從XML文件中提取文本並使用python將其打印到文本文件中。 xml文件中的某些行在其中包含'&#xD'和'& #xA',這些行使用回車符和換行符將行輸出到文本文件。在這裏有Ruby remove 
  和這裏https://stackoverflow.com/questions/28794365/remove-xd-from-xml的答案關於如何在Ruby和PHP中刪除這些字符,以便沒有換行符。我如何在Python中執行此操作。這裏是我的代碼Python從XML中刪除&#xD

with open("xmlfile") as f: 
    doc = parse(f) 
    str = doc.getElementsByTagName("informations")[0].getAttribute("text") 
    print(str) 
    str = str.replace("
", " ").replace("
", " ") 
    print(str) 

下面是在XML文件

"An Airport Contact Method, Is Alter must be one of the following:
- "T" or "F" (boolean true or false) or empty" language="en" 

輸出字符串:

An Airport Contact Method, Is Alter must be one of the following: 
- "T" or "F" (boolean true or false) or empty 
An Airport Contact Method, Is Alter must be one of the following: 
- "T" or "F" (boolean true or false) or empty 
+0

請包括一個簡短的完整程序,演示您遇到的問題。請包括程序的實際輸出和預期輸出。參見[問],但更具體地說,[mcve]。 –

+0

在xml文件中顯示字符串沒有用。顯示'doc.getElementsByTagName(「informations」)[0] .getAttribute(「text」)'返回的值。 – martineau

回答

2

通過任何你正在使用XML庫已解析它的時候,它的已經解決了實體。

更換

str = str.replace("
", " ").replace("
", " ") 

str = str.replace("\r", " ").replace("\n", " ") 

每@馬蒂諾的建議,如果你曾經不知道XML實體是解決什麼字符,你可以嘗試print(repr(str))來獲得更好的畫面d。字符串實際上包含的內容爲parse d。

+0

謝謝,我開始嘗試類似於str.rstrip('\ r \ n'),但仍然在兩行 – gary69

+2

@ user3614578:'print(repr(str))中打印字符串以查看實際存在的內容由XML庫返回(而不是不斷猜測)。 – martineau

+0

用\ r \ n代替 – gary69