我需要找出具有某些属性和名称空间的XML元素的索引(位置)。在我的XML中,有更多具有相同名称的元素,因此唯一可以确定正确元素的方法是通过其属性。
这是我的XML文档的示例:
<mets:mets LABEL="Moderní pedagogika, 2002" TYPE="Monograph"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:mets="http://www.loc.gov/METS/"
xmlns:mods="http://www.loc.gov/mods/v3"
xmlns:ns3="http://www.openarchives.org/OAI/2.0/oai_dc/"
xmlns:ns5="http://www.w3.org/1999/xlink"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.w3.org/2001/XMLSchema-instance http://www.w3.org/2001/XMLSchema.xsd http://www.loc.gov/METS/ http://www.loc.gov/standards/mets/mets.xsd http://www.loc.gov/mods/v3 http://www.loc.gov/standards/mods/v3/mods-3-4.xsd http://www.openarchives.org/OAI/2.0/oai_dc/ http://www.openarchives.org/OAI/2.0/oai_dc.xsd http://www.w3.org/1999/xlink http://www.w3.org/1999/xlink.xsd">
<mets:metsHdr CREATEDATE="2012-12-05T07:42:22" LASTMODDATE="2012-12-05T07:42:22">
<mets:agent ROLE="CREATOR" TYPE="ORGANIZATION">
<mets:name>ABA001</mets:name>
</mets:agent>
<mets:agent ROLE="ARCHIVIST" TYPE="ORGANIZATION">
<mets:name>ABA001</mets:name>
</mets:agent>
</mets:metsHdr>
<mets:dmdSec ID="MODSMD_VOLUME_0001">
.....
</mets:dmdSec>
<mets:dmdSec ID="DCMD_VOLUME_0001">
.....
</mets:dmdSec>
</mets:mets>
在这种情况下,所需索引是此标记的索引<mets:dmdSec ID =“ MODSMD_VOLUME_0001”>
我已经尝试过一些有关list(root).index(dmdSec)的解决方案,但没有成功,因为我无法或不知道如何在其中插入有关属性和名称空间的详细信息
有人可以帮我吗
我假设您正在使用lxml.etree库进行xml解析-如果不是,则可能需要进行一些修改-但原理是相同的:
只需使用:
编辑:
from lxml import etree
root = etree.parse(r'path\to\your\file.xml')
int(root.xpath('count(//*[@ID="MODSMD_VOLUME_0001"]/preceding-sibling::*)+1'))
输出:2
。
请注意,位置是2
不是1
-xpath从1开始计数(与python从0开始计数不同)。您的目标是<mets:dmdSec>
根中的第二个节点。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句