2017-12-21 6 views
1

Ich habe eine XML-Datei wie unten, und ich habe es mit lxml in Tree geparst. Was ich tun möchte, ist Xml-Deklaration von xmlns="http://www.w3.org/TR/html4/" zu xmlns="http://www.w3.org/TR/html5/" zu ändern.Wie ändere ich XML-Namespace mit Lxml in Python?

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

Aber ich konnte das xmlns Attribut oder, um es ändern die tag Eigenschaft durch gesetzt. Jede Hilfe, danke.

Antwort

0

Ich glaube, Sie das table Element lokalisieren und wieder stellen Sie den Attributwert den Zugriff auf das xmlns Attribut über das .attrib Wörterbuch:

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

Ich würde empfehlen, tatsächlich BeautifulSoup für diese Art von Änderungen in der HTML-Struktur mit :

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) 

und es zurückgeben sollte:

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

und wir verwenden immer noch lxml aber innen BeautifulSoup