我有一个XML文件,结构如下:
<Thread THREAD_SEQUENCE="Q268_R16">
<RelQuestion RELQ_ID="Q268_R16">
<RelQSubject>Best Bank.</RelQSubject>
<RelQBody>Hi ti all QL's; What bank you are using? and why? Are you using this bank just because it has an affiliate at home? Regards;</RelQBody>
</RelQuestion>
</Thread>
在XML文件中,有244个RelQBody标记。 我想要做的是获取RelQBody标签内的文本。我尝试过这样的事情:
import xml.dom.minidom
dom = xml.dom.minidom.parse("test.xml")
data = dom.documentElement
question = data.getElementsByTagName("RelQBody")
i=1
for q in question:
print("%i. %s" % (i, q.childNodes[0].data))
i = i+1
但我一直在说错误
Traceback (most recent call last):
File "C:\Users\Administrator\Documents\python\test.py", line 13, in <module>
print("%i. %s" % (i, q.childNodes[0].data))
IndexError: list index out of range
然而,当我尝试这段代码时:
import xml.dom.minidom
dom = xml.dom.minidom.parse("test.xml")
data = dom.documentElement
question = data.getElementsByTagName("RelQBody")
i=1
for q in question:
print("%i" % i)
i = i+1
我的号码是1-244。它与数据集中的完全相同。
那么为什么当我用字符串打印出来并没有字符串时会有区别?也许有人可以告诉我哪个部分我做错了? 我是Python的新手,所以任何帮助都将受到赞赏。感谢。
答案 0 :(得分:1)
我猜怪是class in <tr> tag
,因为其中一个节点可能有0个子节点,调用$no = 1;
while ($row = mysqli_fetch_array($result))
{
$month1=strtotime($row['month']);
$month=date('m-Y',$month1);
$store_name=$row['store_name'];
$netamt1=$row['netamt'];
$netamt11=number_format($netamt1,2);
$usage1=$row['monusage'];
$usage11=number_format($usage1,2);
$answer=$usage1/$netamt1*1000;
$answer1=number_format($answer,2);
$duh = number_format($row['duh'],2);
$total+=$duh;
$avg=$total/$no;
echo "<tr class='y_n';>";
echo "<td>".$no."</td>";
echo "<td>".$store_name."</td>";
echo "<td>".$date2111."</td>";
echo "<td>".$netamt11."</td>";
echo "<td>".$usage11."</td>";
$no++;
echo "<td>".$duh."</td>";
echo "</tr>";
} ?>
<script type="text/javascript">
$('#table_id tr.y_n td').each(function() {
if ($(this).text() >=<?=number_format($avg,2)?>) {
$(this).parent().css('background-color', '#fc9c9c');
}
else
$(this).parent().css('background-color', '#e5f5ff');
});
</script>
</tbody>
<tfoot>
<tr>
<th colspan="5">TOTAL</th>
<th><?=($total)?></th>
</tr>
<tr>
<th colspan="5">AVERAGE</th>
<th><?=number_format($avg,4)?></th></tr>
<tr>
<th colspan="6"><center><?php echo $actionstatus?></center></th>
</tr>
</tfoot>
</table>
会导致IndexError
所以试试这个:
childNodes[0]
答案 1 :(得分:1)
import xml.dom.minidom
dom = xml.dom.minidom.parse("test.xml")
data = dom.documentElement
question = data.getElementsByTagName("RelQBody")
for i,q in enumerate(question):
if len(q.childNodes) > 0:
print("%i. %s" % (i+1, q.childNodes[0].data))