我正在尝试使用xml.etree.ElementTree
查找标签。我不知道确切的位置,所以我必须搜索它。
输入是.Net NuGet包的NuGet-Specifications。
我使用此代码查找了元素,但没有找到它:
import xml.etree.ElementTree as ET
content = ......
tree = ET.fromstring(content)
# none of the following lines are working
tag = tree.find('licenseUrl')
tags = tree.findall('*/licenseUrl')
tags = tree.findall('.//licenseUrl')
tags = tree.findall('licenseUrl')
但是len(tags)
始终为0。
如果我使用正则表达式来查找它,它就像一个符咒:
re.search(r'<licenseUrl>(?P<url>.*?)</licenseUrl>', content, flags=re.DOTALL or re.MULTILINE)
但是不建议使用正则表达式来解析xml。
我在做什么错?
显示工作代码的DEMO。
我使用以下信息时没有走运:
为完整起见,content
的内容:
<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd">
<metadata>
<id>AutoMapper</id>
<version>9.0.0</version>
<authors>Jimmy Bogard</authors>
<owners>Jimmy Bogard</owners>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<licenseUrl>https://github.com/AutoMapper/AutoMapper/blob/master/LICENSE.txt</licenseUrl>
<projectUrl>https://automapper.org/</projectUrl>
<iconUrl>https://s3.amazonaws.com/automapper/icon.png</iconUrl>
<description>A convention-based object-object mapper.</description>
<repository type="git" url="https://github.com/AutoMapper/AutoMapper" commit="53faf3f014802b502f6a49b4c94368f478752f59" />
<dependencies>
<group targetFramework=".NETFramework4.6.1" />
<group targetFramework=".NETStandard2.0">
<dependency id="Microsoft.CSharp" version="4.5.0" exclude="Build,Analyzers" />
<dependency id="System.Reflection.Emit" version="4.3.0" exclude="Build,Analyzers" />
</group>
</dependencies>
<frameworkAssemblies>
<frameworkAssembly assemblyName="Microsoft.CSharp" targetFramework=".NETFramework4.6.1" />
</frameworkAssemblies>
</metadata>
</package>
您的XML具有您未考虑的默认名称空间。此代码应工作:
import xml.etree.ElementTree as ET
content = ......
tree = ET.fromstring(content)
ns = {'ms': 'http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd'}
tags = tree.findall('.//ms:licenseUrl', ns)