.Net 2.0中的IronPython XML-Reader

时间:2013-02-26 10:26:59

标签: python xml ironpython

我创建了一个XML-Reader,它创建了一个非常愚蠢的格式化List,但是goint使用它的脚本需要这样做。

import xml.etree.ElementTree as ET

PATH_IN = "<Path>\sweep.xml"

tree = ET.parse(PATH_IN)
root = tree.getroot()

Input = []
for project in root:

    for design in project:
        list_lvl2 = []
        list_lvl2.append(project.get('name'))
        list_lvl2.append(design.get('name'))
        list_lvl2.append('')

        list_lvl3 = [] 
        for param in design:
            list_lvl4 = []
            list_lvl4.append(param.get('name'))
            list_lvl5 = []
            for steps in param:
                list_lvl5.append(steps.text)
            list_lvl4.append(list_lvl5)
            list_lvl4.append(param.get('unit'))
            list_lvl3.append(list_lvl4)
        list_lvl2.append(list_lvl3)
        Input.append(list_lvl2)

问题是我必须在程序的脚本接口中执行它,该程序在.NET 2.0.50727.5466上使用IronPython 2.6.10920.0。它会引发以下错误:

*Global - Messages
  [error] ImportException: No module named expat; use SimpleXMLTreeBuilder instead  In file "<Path>/sweep.py", line 36 ---- While executing script: <Path>/sweep.py
  [error] Error executing script in <Path>\sweep.py:
  [error] ImportException: No module named expat; use SimpleXMLTreeBuilder instead  In file "<Path>/sweep.py", line 36 ---- While executing script: <Path>/sweep.py
  [error] Error executing script in <Path>\sweep.py:

我不明白的是这个使用相同模块的脚本运行良好:

import xml.etree.ElementTree as ET

path = "<Path>\projects.xml"

root = ET.Element('xml')
projects = oDesktop.GetProjectList()
for i in projects:
    project = ET.SubElement(root,'project')
    project.set('name', i)
    designs = oDesktop.SetActiveProject(i).GetTopDesignList()
    for u in designs:
        design = ET.SubElement(project,'design')
        design.set('name', u)
        vars = oDesktop.SetActiveProject(i).GetDesign(u).GetVariables()
        for z in vars:
            param = ET.SubElement(design,'param')
            param.set('name', z)
            value = ET.SubElement(param,'value')
            value.text = oDesktop.SetActiveProject(i).GetDesign(u).GetVariableValue(z)
f = open(path, "w")
tree = ET.ElementTree(root)
tree.write(f)

f.close()

oDesktop等只是获取数据的特定于程序的函数。 我真的不明白为什么第一个脚本不起作用,我猜是因为NET 2.0。

更新:在查找expat之后,我更加困惑,因为我从来没有在任何地方使用它,我使用的所有elementtree函数都应该支持这个版本的Iron Python。它仍然在这一行tree = ET.parse(PATH_IN)

上给出了expat错误

更新:我尝试使用from elementtree import SimpleXMLTreeBuilder as ET导致:

*Global - Messages
  [error] ImportException: No module named elementtree  In file "<Path>/sweep.py", line 3 ---- While executing script: <Path>/sweep.py
  [error] Error executing script in <Path>\sweep.py:

1 个答案:

答案 0 :(得分:1)

这里的基本问题是ElementTree使用expat进行xml解析,但是不能从IronPython中使用expat(通过CPython包装器可用于Python的C库)。

但是,ElementTree可以使用由不同解析器驱动的不同树构建器,例如, .NET中的XMLReader解析器。搜索“xmlreader treebuilder”会产生this result,它似乎都描述了您的问题提供了使用XMLReader的替代树构建器实现(MIT许可)。