使用ElementTree解析任意XML文件
我有一个模板XML文件,基于我程序输入的数据,我需要生成一个新的XML文件。这个模板里有一些部分需要根据输入的数据重复出现。但是我并不一定知道这些部分的结构或者它们有多少层嵌套。我现在搞不清楚怎么以一种灵活的方式读取这个模板文件,以便让我填充数据,然后再输出。下面是模板文件的一部分:
<Target_Table>
<Target_Name>SF1_T1</Target_Name>
<Target_Mode>
<REP>
<Target_Location_To_Repeat>
<XLocation>nextXREL</XLocation>
<YLocation>nextYREL</YLocation>
</Target_Location_To_Repeat>
<Target_Location_To_Repeat>
<XLocation>nextXREL</XLocation>
<YLocation>nextYREL</YLocation>
</Target_Location_To_Repeat>
</REP>
</Target_Mode>
<Target_Repetitions>1</Target_Repetitions>
<Meas_Window>
<Window_Size>
<XLocation>FOV</XLocation>
<YLocation>FOV</YLocation>
</Window_Size>
<Window_Location>
<XLocation>firstXREL</XLocation>
<YLocation>firstYREL</YLocation>
</Window_Location>
</Meas_Window>
<Box_Orientation>90</Box_Orientation>
<First_Feature Value="Space" />
<Meas_Params_Definition>
<Number_Of_Lines Value="Auto" />
<Number_Of_Pixels_Per_Line Value="Auto" />
<Averaging_Factor Value="1" />
</Meas_Params_Definition>
<Number_Of_Edges>1</Number_Of_Edges>
<Edge_Pair>
<Edge_Pair_Couple>
<First_Edge>1</First_Edge>
<Second_Edge>1</Second_Edge>
</Edge_Pair_Couple>
<Nominal_Corrected_Value>0</Nominal_Corrected_Value>
</Edge_Pair>
<Categories>
<Material_Type />
<Meas_Type />
<Category_Type />
<Other_Type />
</Categories>
<Bias>0</Bias>
<Template_Target_Name>SF_IMAQ_Template_Target</Template_Target_Name>
<Template_Target_PPL>
<Process>PC2</Process>
<Product>PD2</Product>
<Layer>L2</Layer>
</Template_Target_PPL>
<Meas_Auto_Box>
<Error_Code>0</Error_Code>
<Measured_CD>0</Measured_CD>
<Constant_NM2Pix>true</Constant_NM2Pix>
</Meas_Auto_Box>
<Meas_Box_Pix_Size_X>PixelSize</Meas_Box_Pix_Size_X>
<Macro_CD>0</Macro_CD>
</Target_Table>
我需要把整个Target_Table部分重复多次,并且在每个Target_Table里面,我还需要把REP部分重复多次。我想写一个程序,这样如果模板发生变化(比如增加了更多的嵌套层级),我就不需要修改我的程序。但是我觉得我必须完全了解文件的结构才能读取和输出它。这是真的吗,还是我漏掉了什么?有没有办法写一个程序,可以读取一个标签和嵌套层级都未知的文件?
2 个回答
0
这是一个使用 BeautifulSoup 的例子:
import sys
from bs4 import BeautifulSoup
file = sys.argv[1]
handler = open(file).read()
soup = BeautifulSoup(handler)
for table in soup.find_all("target_table"):
for loc in table.find_all("rep"):
print loc.xlocation.string + ", " + loc.ylocation.string
输出结果
nextXREL, nextYREL
4
使用ElementTree:
import xml.etree.ElementTree as et
filehandler = open("file.xml","r")
raw_data = et.parse(filehandler)
data_root = raw_data.getroot()
filehandler.close()
for children in data_root:
for child in children:
print(child.tag, child.text, children.tag, children.text)
这样你就能看到XML标签和标签里面的相关文本的整体情况。你可以添加更多的循环,深入到树的更深层次,并检查是否有子节点包含更深的层级。我觉得这种方法很有用,特别是当XML标签的名称不固定,或者不遵循已经知道的标准时。