2011-11-10 16 views
3

私はいくつかのXMLファイルを試して操作するためにPythonのminidomライブラリを使用しています。 「これはいくつかの情報です!」Python Minidom:ノードの値を変更する

<document> 
    <item> 
      <link>http://www.this-is-a-url.com/</link> 
      <description>This is some information!</description> 
    </item> 

    <item> 
      <link>http://www.this-is-a-url.com/</link> 
      <description>This is some information!</description> 
    </item> 

    <item> 
      <link>http://www.this-is-a-url.com/</link> 
      <description>This is some information!</description> 
    </item> 
</document> 

、「説明」の値をとるので、両方が言う「リンク」に入れて私は何をする必要がある。ここではサンプルファイルです。私はそうのようにそれを行うことを試みた:

#!/usr/bin/python 

from xml.dom.minidom import parse 

xmlData = parse("file.xml") 

itmNode = xmlData.getElementsByTagName("item") 
for n in itmNode: 
    n.childNodes[1] = n.childNodes[3] 
    n.childNodes[1].tagName = "link" 
print xmlData.toxml() 

しかし「n.childNodes [1] = n.childNodes [3]」「n.childNodes [私が行うときに、2つのノードをリンクするようです1] .tagName = "link" "名前を修正する両方の子ノードが" description "の前に" link "になります。

さらに、「n.childNodes [1] .nodeValue」を使用すると、変更は機能せず、XMLは元の形式で印刷されます。私は間違って何をしていますか?

答えて

5

xml.dom.minidomでDOMを修正できるかどうかはわかりません(新しい値でドキュメント全体を作成することはできます)。あなたはxml.etree.ElementTreeに基づくソリューションを受け入れる場合

とにかく、(私は強くそれが親しみやすいインターフェースを提供するので、それを使用することをお勧めします)、その後、あなたは次のコードを使用することができます実際に

from xml.etree.ElementTree import ElementTree, dump 

tree = ElementTree() 
tree.parse('file.xml') 

items = tree.findall('item') 
for item in items: 
    link, description = list(item) 
    link.text = description.text 

dump(tree) 
+0

を、次のことができます。 有用なユーザーがminidomで変更する方法を示しました。 http://stackoverflow.com/questions/13588072/python-minidom-xml-how-to-set-node-text-with-minidom-api?lq=1 –

+0

@WarrenPそれは面白いです。共有してくれてありがとう。 – jcollado

関連する問題