[英]finding minimum and maximum element value from XML attributes using python
我正在尝试将XML文件转换为可可样式json文件。 这是我的XML文件的样子
<Annotations MicronsPerPixel="0.466667">
<Annotation Id="1" Name="" ReadOnly="0" NameReadOnly="0" LineColorReadOnly="0" Incremental="0" Type="4" LineColor="65280" Visible="1" Selected="1" MarkupImagePath="" MacroName="">
<Attributes/>
<Regions>
<RegionAttributeHeaders>
<AttributeHeader Id="9999" Name="Region" ColumnWidth="-1"/>
<AttributeHeader Id="9997" Name="Length" ColumnWidth="-1"/>
<AttributeHeader Id="9996" Name="Area" ColumnWidth="-1"/>
<AttributeHeader Id="9998" Name="Text" ColumnWidth="-1"/>
<AttributeHeader Id="1" Name="Description" ColumnWidth="-1"/>
</RegionAttributeHeaders>
<Region Id="1" Type="0" Zoom="0.500000" Selected="0" ImageLocation="" ImageFocus="-1" Length="2243.6" Area="342402.0" LengthMicrons="1047.0" AreaMicrons="74567.5" Text="Benign" NegativeROA="0" InputRegionId="0" Analyze="1" DisplayId="1">
<Attributes>
<Attribute Name="1" Id="0" Value="Benign"/>
</Attributes>
<Vertices>
<Vertex X="7398" Y="21614" Z="0"/>
<Vertex X="7396" Y="21614" Z="0"/>
<Vertex X="7392" Y="21636" Z="0"/>
<Vertex X="7388" Y="21656" Z="0"/>
<Vertex X="7386" Y="21660" Z="0"/>
<Vertex X="7384" Y="21666" Z="0"/>
<Vertex X="7384" Y="21670" Z="0"/>
<Vertex X="7384" Y="21672" Z="0"/>
<Vertex X="7384" Y="21674" Z="0"/>
<Vertex X="7382" Y="21674" Z="0"/>
<Vertex X="7382" Y="21676" Z="0"/>
<Vertex X="7382" Y="21678" Z="0"/>
<Vertex X="7382" Y="21680" Z="0"/>
<Vertex X="7382" Y="21682" Z="0"/>
<Vertex X="7380" Y="21682" Z="0"/>
<Vertex X="7380" Y="21684" Z="0"/>
<Vertex X="7380" Y="21686" Z="0"/>
<Vertex X="7380" Y="21688" Z="0"/>
<Vertex X="7380" Y="21690" Z="0"/>
<Vertex X="7378" Y="21690" Z="0"/>
<Vertex X="7378" Y="21694" Z="0"/>
<Vertex X="7378" Y="21696" Z="0"/>
</Vertices>
</Region
</Regions>
<Plots/>
</Annotation>
从该文件中,我必须提取最小和最大X和Y顶点。
我是python的初学者,也是第一次解析xml文件
我尝试了下面的代码以提取最小值x
xml_file = os.path.join(xml_path, f)
print(xml_file)
tree = ET.parse(xml_file)
root = tree.getroot()
#doc = etree.parse(filename)
for elem in root:
#print(elem,'-1')
for child in elem:
#print(child,'-2')
if child.tag=='Regions':
for gchild in child:
if gchild.tag=='Region':
id=gchild.get('Id')
print(id)
for subelem in gchild:
current_sub=subelem.tag
print(current_sub,'-4')
if current_sub=='Vertices':
for vertex in subelem:
minx=100000
for v in vertex.tag:
x=int(vertex.get('X'))
if x<minx:
minx=x
else:
continue
print(minx)
但是,我没有得到预期的结果。 有没有更短更清洁的方式在python中做到这一点。 通过此代码,我将所有X坐标作为我的minx输出
同样,我必须获取max_x , min_y和max_x的值才能创建边界框。
arrX, arrY = [], []
for vertex in root.findall('Vertex'):
arrX.append(int(vertex.get('X')))
arrY.append(int(vertex.get('Y')))
minX, maxX = min(arrX), max(arrX)
minY, maxY = min(arrY), max(arrY)
如果您的XML中没有namespace
,则此方法应该有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.