2015-04-28 23 views
0

我使用LXMLLXML:與符號文本

我使用lxml的解析XML文件並重新寫回一個新的XML文件中的問題。

輸入文件:

<tag1> 
    <tag2 attr1="a1">&quot; example text &quot;</tag2> 
    <tag3> 
    <tag4 attr2="a2">&quot; example text &quot;</tag4> 
    <tag5> 
     <tag6 attr3="a3">&apos; example text &apos;</tag6> 
    </tag5> 
    </tag3> 
</tag1> 

腳本:

from lxml import etree 
    parser = etree.XMLParser(remove_comments=False,strip_cdata=False,resolve_entities=False) 
    tree = etree.parse("input.xml") 
    tree.write("out.xml") 

輸出:

<tag1> 
    <tag2 attr1="a1"> " example text " </tag2> 
    <tag3> 
    <tag4 attr2="a2"> " example text " </tag4> 
    <tag5> 
     <tag6 attr3="a3"> ' example text ' </tag6> 
    </tag5> 
    </tag3> 
</tag1> 

我想保留&quot;&apos;。我甚至嘗試過使用

f = open('output.xml', 'w') 
f.write(etree.tostring(tree1.getroot(),encoding="UTF-8",xml_declaration=False)) 
f.close() 

但是他們都沒有解決這個問題。

然後我試着用手動&quot;更換「。

root = tree.getroot() 
tag_elements = root.iter() 
for tag in tag_elements: 
     tag_text = tag.text 
     if tag_text is not None: 
       tag_text1 = tag_text.replace("\"","&quot;") 
       tag.text = tag_text1 

但是這給了下面的輸出

<tag1> 
    <tag2 attr1="a1"> &amp;quot; example text &amp;quot; </tag2> 
    <tag3> 
    <tag4 attr2="a2"> &amp;quot; example text &amp;quot; </tag4> 
    <tag5> 
     <tag6 attr3="a3"> &apos; example text &apos; </tag6> 
    </tag5> 
    </tag3> 
</tag1> 

它取代了&與&amp;。我很困惑在這裏。請幫我解決

回答

0

&amp;是字符&的xml編碼&quot;是字符"的xml編碼。字符"'不需要編碼,所以lxml不會對它們進行編碼。

您是否嘗試過再次解碼文檔?它應該像你期望的那樣工作。如果您需要再次對文檔中的字符串進行編碼(將&轉換爲&amp;等),請在生成新的xml文檔之前使用lxml樹中的單個字符串進行編碼。