2017-12-21 19 views
1

私は以下のようなXMLファイルを持っており、それをTreeにlxmlで解析しました。 xml宣言をxmlns="http://www.w3.org/TR/html4/"からxmlns="http://www.w3.org/TR/html5/"に変更します。 Pythonでlxmlを使ってXML名前空間を変更するには?

<table xmlns="http://www.w3.org/TR/html4/"> 
    <tr> 
     <td>Apples</td> 
     <td>Bananas</td> 
    </tr> 
</table> 

は、しかし、私は xmlns属性を取得または設定 tagプロパティでそれを変更することができませんでした。どんな助け、ありがとう。

答えて

0

私はあなたがtable要素を検索し、.attrib辞書を経由してxmlns属性にアクセスして再設定された属性値ができると思う:

In [1]: from lxml import html 

In [2]: data = """<html><body><table xmlns="http://www.w3.org/TR/html4/"> 
    ...: <tr> 
    ...:  <td>Apples</td> 
    ...:  <td>Bananas</td> 
    ...: </tr> 
    ...: </table></body></html>""" 

In [3]: root = html.fromstring(data) 

In [4]: root.find('.//table').attrib['xmlns'] = "http://www.w3.org/TR/html5/" 

In [5]: print(html.tostring(root, encoding='unicode', pretty_print=True)) 
<html><body><table xmlns="http://www.w3.org/TR/html5/"> 
    <tr> 
     <td>Apples</td> 
     <td>Bananas</td> 
    </tr> 
</table></body></html> 
0

私は実際にHTMLの構造に変化のこの種のBeautifulSoupを使用することをお勧めします:

from bs4 import BeautifulSoup 
t = """ 
<table xmlns="http://www.w3.org/TR/html4/"> 
<tr> 
    <td>Apples</td> 
    <td>Bananas</td> 
</tr> 
</table> 
""" 
soup = BeautifulSoup(t, 'lxml') 
soup.table['xmlns'] = 'http://www.w3.org/TR/html5/' 
print(soup) 

、それは返す必要があります:

<html><body><table xmlns="http://www.w3.org/TR/html5/"> 
<tr> 
<td>Apples</td> 
<td>Bananas</td> 
</tr> 
</table> 
</body></html> 

ですが、まだlxmlが使用されていますが、BeautifulSoupの内部

関連する問題