如何使用jython迭代org.w3c.dom.NodeList?

时间:2013-05-03 22:29:14

标签: java dom jython-2.5

我正在使用org.w3c.dom处理一些xml文档。我正在使用jython 2.5.1来实现它。

我的xml文档(EmployeeInfo.xml)的一部分就像:

<employees>
    <employee id="1">
      <name>ABC</name>
      <title>Software Engineer</title>
    </employee> 
    <employee id="2">
      <name>DEF</name>
      <title>Systems Engineer</title>
    </employee>
    <employee id="3">
      <name>GHI</name>
      <title>QA Engineer</title>
    </employee>
    ......
</employees>

我读取和解析xml的jython代码如下:

import sys, logging
logging.basicConfig(level=logging.INFO)

from java.io import File
from javax.xml.parsers import DocumentBuilder
from javax.xml.parsers import DocumentBuilderFactory
from org.w3c.dom import Document
from org.w3c.dom import Element
from org.w3c.dom import Node
from org.w3c.dom import NodeList

// ... some code 

file = "C:/Users/Adminstrator/Doc/EmployeeInfo.xml"
doc = File(file)
if doc.exists():
    docFactory = DocumentBuilderFactory.newInstance()
    docFactory.setNamespaceAware(True)
    docBuilder = docFactory.newDocumentBuilder()

    if doc.endswith(".xml"):
        logging.info(" -- Reading " + doc)
        employeeDoc = docBuilder.parse(doc)

        if employeeDoc != None:
            employees = employeeDoc.getElementsByTagNameNS("*","employee")
            if employees != None:
                for employee in employees:
                    logging.info(employee.getChildNodes().getLength())
            else:
                logging.warn("Failed to get the employee from " + doc)
        else:
            logging.warn("Failed to parse the document " + doc)

else:
    logging.warn("Failed to find the specified document" + doc + ", please check the path!")

当我运行此脚本时,出现错误:

TypeError: 'org.apache.xerces.dom.DeepNodeListImpl' object is not iterable

指的是:

for employee in employees:

似乎它会自动将'employees'视为jython的NodeList而不是org.w3c.dom.NodeList ......

我在网上搜索过这个问题,但我对这个问题的了解很少......有人可以帮我这个吗?提前致谢!

2 个答案:

答案 0 :(得分:1)

我使用while循环来替换for循环,因为很少使用for(int i = 0; i

所以我用过:

i = 0
while i < employees.getLength:
    employee = employees.item(i)
    i = i + 1
....

答案 1 :(得分:0)

org.apache.xerces.dom.DeepNodeListImpl 这应该有效:

for (int i; i < employees.getLength(); i++) {
    Node employee = employees.item(i);
    ....
}