如何在 XML 文件中按名称查找元素
How can I find an element by name in a XML file
我正在尝试解析 ICD-10 代码并给出一个代码,标识:描述,parent,children(如果有)。给定我正在解析的较大文件的样本:
我正在解析的较大 XML 文件的示例
data = ```<diag>
<name>A00</name>
<desc>Cholera</desc>
<diag>
<name>A00.0</name>
<desc>Cholera due to Vibrio cholerae 01, biovar cholerae</desc>
<inclusionTerm>
<note>Classical cholera</note>
</inclusionTerm>
</diag>
<diag>
<name>A00.1</name>
<desc>Cholera due to Vibrio cholerae 01, biovar eltor</desc>
<inclusionTerm>
<note>Cholera eltor</note>
</inclusionTerm>
</diag>
<diag>
<name>A00.9</name>
<desc>Cholera, unspecified</desc>
</diag>
</diag>```
如何在 python 中编写代码,通过搜索其名称为我提供特定元素? (示例:我正在寻找代码 A00.0,我希望程序打印找到的 A00.0 代码,以及描述和 inclusionTerm。
如@mzjn 所述,您可以使用 xml.etree
,它是 Python 标准库的一部分。特别是,您可能想查看 XPath Support:
from xml.etree import ElementTree as ET
root = ET.parse('myfile.xml') # alternatively use ET.fromstring()
# Find diagnosis by "name" (ICD-10 code)
diag = root.find(".//*[name='A00.0']")
# Print out some information ("name" and "desc" tags)
print(diag.find('name').text)
print(diag.find('desc').text)
XPath 的解释.//*[name='A00.0']
.
select当前节点(XML根元素)
//
select 所有子元素(递归搜索树)
*
select 所有子元素
[name='A00.0']
select 元素有一个名为 name
的子元素,其文本为 A00.0
所以用这个 XPath 调用 root.find()
找到这个节点:
<diag>
<name>A00.0</name>
<desc>Cholera due to Vibrio cholerae 01, biovar cholerae</desc>
<inclusionTerm>
<note>Classical cholera</note>
</inclusionTerm>
</diag>
我正在尝试解析 ICD-10 代码并给出一个代码,标识:描述,parent,children(如果有)。给定我正在解析的较大文件的样本:
我正在解析的较大 XML 文件的示例
data = ```<diag>
<name>A00</name>
<desc>Cholera</desc>
<diag>
<name>A00.0</name>
<desc>Cholera due to Vibrio cholerae 01, biovar cholerae</desc>
<inclusionTerm>
<note>Classical cholera</note>
</inclusionTerm>
</diag>
<diag>
<name>A00.1</name>
<desc>Cholera due to Vibrio cholerae 01, biovar eltor</desc>
<inclusionTerm>
<note>Cholera eltor</note>
</inclusionTerm>
</diag>
<diag>
<name>A00.9</name>
<desc>Cholera, unspecified</desc>
</diag>
</diag>```
如何在 python 中编写代码,通过搜索其名称为我提供特定元素? (示例:我正在寻找代码 A00.0,我希望程序打印找到的 A00.0 代码,以及描述和 inclusionTerm。
如@mzjn 所述,您可以使用 xml.etree
,它是 Python 标准库的一部分。特别是,您可能想查看 XPath Support:
from xml.etree import ElementTree as ET
root = ET.parse('myfile.xml') # alternatively use ET.fromstring()
# Find diagnosis by "name" (ICD-10 code)
diag = root.find(".//*[name='A00.0']")
# Print out some information ("name" and "desc" tags)
print(diag.find('name').text)
print(diag.find('desc').text)
XPath 的解释.//*[name='A00.0']
.
select当前节点(XML根元素)//
select 所有子元素(递归搜索树)*
select 所有子元素[name='A00.0']
select 元素有一个名为name
的子元素,其文本为A00.0
所以用这个 XPath 调用 root.find()
找到这个节点:
<diag>
<name>A00.0</name>
<desc>Cholera due to Vibrio cholerae 01, biovar cholerae</desc>
<inclusionTerm>
<note>Classical cholera</note>
</inclusionTerm>
</diag>