textNode总是一个节点的firstChild吗?

时间:2015-02-04 10:10:48

标签: python xml dom

当使用XML DOM时,.firstChild.data方法是否总是返回节点的textNode的内容,如果节点有一个?

在XML文件中:

 <rtcincident>CRASH

Python代码:

incidentNameInput = str(raw_input("Enter incident name: ")).upper().rstrip()
//For this example, user inputs 'crash'.

rtcIncidentNameList = xmlDoc.getElementsByTagName("rtcincident")

for i in range (0, rtcIncidentNameList.length):
    if rtcIncidentNameList[i].firstChild.data == incidentNameInput:
        print("found incident")

但是,永远不会调用最终打印,因为永远不会满足if语句条件。

2 个答案:

答案 0 :(得分:1)

不,元素节点的子节点可以是几种类型:Comment,CDATASection,Text,Element,ProcessingInstruction。元素节点可以具有子节点的任何计数和组合。

根据DOM标准data在CharacterData超类中实现。 Text,CDATASection和ProcessingInstruction扩展了该类。

答案 1 :(得分:1)

不,这是一个例子:

<span><span></span> trailing text</span>

外部span有一个firstChild,它是一个元素,而不是一个文本节点:内部span。就其本身而言,内部span具有firstChild === null

如果您正在使用DOM 3实现,并且您想要所有子节点的节点的文本内容,则可以使用textContent属性。有关详细信息和浏览器支持图表,请参阅此MDN article。如果您使用的是DOM 2或更低版本的实现,则必须通过遍历节点来自行计算。