Python으로 minidom으로 요소 값 가져 오기
Python에서 Eve Online API 용 GUI 프런트 엔드를 만들고 있습니다.
서버에서 XML 데이터를 성공적으로 가져 왔습니다.
"이름"이라는 노드에서 값을 가져 오려고합니다.
from xml.dom.minidom import parse
dom = parse("C:\\eve.xml")
name = dom.getElementsByTagName('name')
print name
이것은 노드를 찾는 것처럼 보이지만 출력은 다음과 같습니다.
[<DOM Element: name at 0x11e6d28>]
노드의 값을 인쇄하려면 어떻게해야합니까?
그것은 단지
name[0].firstChild.nodeValue
아마도 당신이 원하는 텍스트 부분이라면 아마도 이와 같은 것입니다.
from xml.dom.minidom import parse
dom = parse("C:\\eve.xml")
name = dom.getElementsByTagName('name')
print " ".join(t.nodeValue for t in name[0].childNodes if t.nodeType == t.TEXT_NODE)
노드의 텍스트 부분은 요청한 노드의 자식 노드로 배치 된 노드로 간주됩니다. 따라서 모든 하위 항목을 살펴보고 텍스트 노드 인 모든 하위 노드를 찾을 수 있습니다. 노드에는 여러 텍스트 노드가있을 수 있습니다. 예.
<name>
blabla
<somestuff>asdf</somestuff>
znylpx
</name>
'blabla'와 'znylpx'를 모두 원합니다. 따라서 "".join (). 공백을 개행 문자로 대체하거나 아무것도 사용하지 않을 수 있습니다.
이런 식으로 사용할 수 있습니다.
doc = parse('C:\\eve.xml')
my_node_list = doc.getElementsByTagName("name")
my_n_node = my_node_list[0]
my_child = my_n_node.firstChild
my_text = my_child.data
print my_text
위의 대답은 정확합니다.
name[0].firstChild.nodeValue
그러나 나에게 다른 사람들과 마찬가지로 내 가치는 나무 아래에 있었다.
name[0].firstChild.firstChild.nodeValue
이것을 찾기 위해 다음을 사용했습니다.
def scandown( elements, indent ):
for el in elements:
print(" " * indent + "nodeName: " + str(el.nodeName) )
print(" " * indent + "nodeValue: " + str(el.nodeValue) )
print(" " * indent + "childNodes: " + str(el.childNodes) )
scandown(el.childNodes, indent + 1)
scandown( doc.getElementsByTagName('text'), 0 )
Inkscape로 만든 간단한 SVG 파일에 대해 이것을 실행하면 다음과 같은 결과가 나타납니다.
nodeName: text
nodeValue: None
childNodes: [<DOM Element: tspan at 0x10392c6d0>]
nodeName: tspan
nodeValue: None
childNodes: [<DOM Text node "'MY STRING'">]
nodeName: #text
nodeValue: MY STRING
childNodes: ()
nodeName: text
nodeValue: None
childNodes: [<DOM Element: tspan at 0x10392c800>]
nodeName: tspan
nodeValue: None
childNodes: [<DOM Text node "'MY WORDS'">]
nodeName: #text
nodeValue: MY WORDS
childNodes: ()
나는 xml.dom.minidom을 사용했고, 다양한 필드는 이 페이지 인 MiniDom Python에서 설명합니다.
나는이 질문이 지금 꽤 오래되었다는 것을 알고 있지만 ElementTree 로 더 쉽게 시간을 보낼 수 있다고 생각했습니다.
from xml.etree import ElementTree as ET
import datetime
f = ET.XML(data)
for element in f:
if element.tag == "currentTime":
# Handle time data was pulled
currentTime = datetime.datetime.strptime(element.text, "%Y-%m-%d %H:%M:%S")
if element.tag == "cachedUntil":
# Handle time until next allowed update
cachedUntil = datetime.datetime.strptime(element.text, "%Y-%m-%d %H:%M:%S")
if element.tag == "result":
# Process list of skills
pass
나는 그것이 매우 구체적이지 않다는 것을 알고 있지만 방금 그것을 발견했으며 지금까지 미니 돔보다 머리를 돌리는 것이 훨씬 쉽습니다 (많은 노드가 본질적으로 공백이기 때문에).
예를 들어, 예상했던대로 태그 이름과 실제 텍스트가 함께 있습니다.
>>> element[0]
<Element currentTime at 40984d0>
>>> element[0].tag
'currentTime'
>>> element[0].text
'2010-04-12 02:45:45'e
비슷한 경우가 있었는데 나를 위해 일한 것은 다음과 같습니다.
name.firstChild.childNodes [0] .data
XML is supposed to be simple and it really is and I don't know why python's minidom did it so complicated... but it's how it's made
Here is a slightly modified answer of Henrik's for multiple nodes (ie. when getElementsByTagName returns more than one instance)
images = xml.getElementsByTagName("imageUrl")
for i in images:
print " ".join(t.nodeValue for t in i.childNodes if t.nodeType == t.TEXT_NODE)
The question has been answered, my contribution consists in clarifying one thing that may confuse beginners:
Some of the suggested and correct answers used firstChild.data
and others used firstChild.nodeValue
instead. In case you are wondering what is the different between them, you should remember they do the same thing because nodeValue
is just an alias for data
.
The reference to my statement can be found as a comment on the source code of minidom:
#
nodeValue
is an alias fordata
참고URL : https://stackoverflow.com/questions/317413/get-element-value-with-minidom-with-python
'Programming' 카테고리의 다른 글
한 번의 작업으로 여러 파일 다운로드 (0) | 2020.08.18 |
---|---|
int num = Integer.getInteger (“123”)에서 NullPointerException이 발생하는 이유는 무엇입니까? (0) | 2020.08.18 |
UITableView의 tableHeaderView 크기를 조정하는 방법은 무엇입니까? (0) | 2020.08.18 |
LIKE 문을 사용하여 PDO 매개 변수가있는 쿼리를 어떻게 생성합니까? (0) | 2020.08.18 |
Linux, 그룹 권한이 있는데도 쓸 수없는 이유는 무엇입니까? (0) | 2020.08.18 |