相关疑难解决方法(0)

使用Python使用minidom获取Element值

我正在为Python中的Eve Online API创建一个GUI前端.

我已成功从其服务器中提取XML数据.

我试图从名为"name"的节点中获取值:

from xml.dom.minidom import parse
dom = parse("C:\\eve.xml")
name = dom.getElementsByTagName('name')
print name
Run Code Online (Sandbox Code Playgroud)

这似乎找到了节点,但输出如下:

[<DOM Element: name at 0x11e6d28>]
Run Code Online (Sandbox Code Playgroud)

我怎么能让它打印节点的值?

python dom minidom

100
推荐指数
5
解决办法
13万
查看次数

如何在python中的xml.minidom中没有任何孩子的xml节点上设置文本?

昨天我问如何使用 minidom用子节点替换节点上的文本

今天我也试图<node/><node>text</node>

不幸的是,我觉得我的结果是一个可怕的黑客:

import xml.dom.minidom
from   xml.dom.minidom import Node

def makenode(text):
    n = xml.dom.minidom.parseString(text)
    return n.childNodes[0]

def setText(node, newText):
    if node.firstChild==None:
        str =  node.toxml();
        n = len(str)
        str = str[0:n-2]+'>'+newText+'</'+node.nodeName+'>'   #DISGUSTINGHACK!
        node.parentNode.replaceChild(  makenode(str),node )
        return
    if node.firstChild.nodeType != node.TEXT_NODE:
        raise Exception("setText: node "+node.toxml()+" does not contain text")
    node.firstChild.replaceWholeText(newText)

def test():
    olddoc = '<test><test2/></test>'
    doc=xml.dom.minidom.parseString(olddoc)
    node = doc.firstChild.firstChild  # <test2/>
    print "before:",olddoc
    setText(node,"textinsidetest2")
    newdoc =  doc.firstChild.toxml()
    print "after: ", newdoc


 #  desired result:
 # newdoc='<test><test2>textinsidetest2</test2></test>' …
Run Code Online (Sandbox Code Playgroud)

python xml

4
推荐指数
1
解决办法
2257
查看次数

Python Minidom:改变Node的价值

我正在使用Python的minidom库来尝试和操作一些XML文件.这是一个示例文件:

<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>
Run Code Online (Sandbox Code Playgroud)

我需要做的是取"描述"中的值并将其放入"链接"中,这样​​两者都说"这是一些信息!".我试过这样做:

#!/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()
Run Code Online (Sandbox Code Playgroud)

但是"n.childNodes [1] = n.childNodes [3]"似乎将两个节点链接在一起,所以当我执行"n.childNodes [1] .tagName ="link""来更正名称时两个子节点变为"链接"之前它们都是"描述".

此外,如果我使用"n.childNodes [1] .nodeValue",则更改不起作用,并且XML以其原始形式打印.我究竟做错了什么?

python xml minidom

3
推荐指数
1
解决办法
8782
查看次数

标签 统计

python ×3

minidom ×2

xml ×2

dom ×1