簡體   English   中英

Python XML 元素屬性錯誤:'NoneType' object 沒有屬性'文本'

[英]Python XML Element AttributeError: 'NoneType' object has no attribute 'text'

我正在嘗試解析以下 xml 文件。

<xml version="1">
    <nodes>
    1      -2.50000000E+01       0.00000000E+00       5.00000000E+00
    </nodes>
</xml>

我想檢索該文件中元素nodes內的值。 我嘗試了以下代碼:

import pandas as pd
import xml.etree.ElementTree as ET

xtree = ET.parse("SafePGInput_t.dat")
xroot = xtree.getroot()

for node in xroot:
    s_nodes = node.find('nodes')
    print(s_nodes.text)

返回的是AttributeError: 'NoneType' object has no attribute 'text' 我以為它會返回一個字符串。 只需打印s_nodes返回None 如何獲取元素nodes中四個值的文本? 如果可能,我想將這些值加載到 pandas 中,因為我需要計算一個新行。 當使用解析器“lxml”時,實際的nodes元素包含大量值超過pd.read_xml限制的行。

任何幫助,將不勝感激。

親切的問候,

阿里

如果要檢查當前節點的標簽,請使用:

node.tag

要獲取內容,如果節點是您想要的,請使用

node.text

在你的情況下,也許你想要:

import pandas as pd
import xml.etree.ElementTree as ET

xtree = ET.parse("trash/d.xml")
xroot = xtree.getroot()
for node in xroot:
    if node.tag == "nodes":
        print(node.text)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM