[英]Python get XML Attributes from multiple nodes
输入XML
<component>
<section classCode="DOCSECT" moodCode="EVN">
<organizer classCode="CLUSTER" moodCode="EVN">
<code code="46680005" codeSystem="2.16.840.1.113883.6.96" displayName="Vital signs"/>
<component>
<observation classCode="OBS" moodCode="EVN">
<templateId root="2.16.840.1.113883.10.20.22.4.27"/>
<id root="fe4dc35f-ea98-4d3c-844f-3098e3419a59"/>
<code code="8302-2" displayName="Height"/>
<statusCode code="completed"/>
<effectiveTime value="20110130"/>
<value unit="Inches" value="61.2598" xsi:type="PQ"/>
</observation>
</component>
<component>
<observation classCode="OBS" moodCode="EVN">
<templateId root="2.16.840.1.113883.10.20.22.4.27"/>
<id root="95f747ac-c3f5-4de0-84eb-29f20d68e571"/>
<code code="3141-9" displayName="Weight"/>
<statusCode code="completed"/>
<effectiveTime value="20110130"/>
<value unit="lbs" value="108.00" xsi:type="PQ"/>
</observation>
</component>
</organizer>
</section>
</component>
输入命名空间
<ClinicalDocument xmlns="urn:hl7-org:v3" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" moodCode="EVN">
码
from xml.etree import ElementTree
tree = ElementTree.parse(sample_string)
root = tree.getroot()
for each in root.findall(".//{urn:hl7-org:v3}observation/{urn:hl7-org:v3}code[@displayName='Height']"):
print(each.attrib)
乌普特
{'code': '8302-2', 'displayName': 'Height'}
题
我想访问有效时间value =“”,code =“”,displayName =“”,unit =“”和value =“”。 但是由于存在与代码和值同名的多个属性,所以我不知道如何到达特定元素。 我不希望帮助格式化输出,但是要画出清晰的图片,最后,我试图以表格形式输出。
date, code, display_name, value, unit
20110130, 8302-2, Height, 61.2598, Inches
任何帮助,我们都感激不尽。
这是获取预期结果的Xpath 1.0查询。 由于OP没有发布完整的示例,因此使用不带名称空间的XML进行了测试
"//observation[code[@displayName="Height"]]/*[self::effectiveTime | self::value | self::code]/@*[name()="value" or name()="unit" or name()="displayName"]
XPath部分的详细信息:
"//observation[code[@displayName="Height"]]"
"*[self::effectiveTime | self::value | self::code]"
子节点。 表示任何有效时间,值或代码的节点。 "@*[name()="value" or name()="unit" or name()="displayName"]"
在命令行上测试
xmllint --xpath '//observation[code[@displayName="Height"]]/*[self::effectiveTime | self::value | self::code]/@*[name()="value" or name()="unit" or name()="displayName"]' test.xml | tr ' ' '\n'; echo
结果,属性按文档顺序显示:
displayName="Height"
value="20110130"
unit="Inches"
value="61.2598"
发生故障时,获取包含期望值的节点,然后将其作为参考找到它们
// find an observation node containing a code node with a displayName attribute = "Height"
refNode = root.find(".//{urn:hl7-org:v3}observation[{urn:hl7-org:v3}code[@displayName='Height']]")
for each in refNode.findall("some xpath"):
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.