如何使用lxml针对多个xsd模式进行验证?

2024-05-19 12:23:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个单元测试,通过获取xsd模式并使用python的lxml库验证生成的sitemapxml:

下面是关于我的根元素的一些元数据:

xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"
xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 
http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd 
http://www.google.com/schemas/sitemap-image/1.1 
http://www.google.com/schemas/sitemap-image/1.1/sitemap-image.xsd"

这个测试代码:

^{pr2}$

验证失败的示例XML:

<?xml version="1.0" encoding="UTF-8"?>
<urlset
  xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
  xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="
    http://www.sitemaps.org/schemas/sitemap/0.9
    http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd
    http://www.google.com/schemas/sitemap-image/1.1
    http://www.google.com/schemas/sitemap-image/1.1/sitemap-image.xsd"
>
  <url>
    <loc>https://www.example.com/press</loc>
    <lastmod>2016-08-11</lastmod>

    <changefreq>weekly</changefreq>
  </url>

  <url>
    <loc>https://www.example.com/about-faq</loc>
    <lastmod>2016-08-11</lastmod>

    <changefreq>weekly</changefreq>
  </url>


</urlset>

当我刚有一个常规的站点地图时,一切都很好,但是当我添加图像站点地图标记assertValid时开始失败,原因是:

E   DocumentInvalid: Element '{http://www.google.com/schemas/sitemap-image/1.1}image': No matching global element declaration available, but demanded by the strict wildcard., line 12

或者:

E   DocumentInvalid: Element '{http://www.sitemaps.org/schemas/sitemap/0.9}urlset': No matching global declaration available for the validation root., line 6

Tags: orgimagecomhttpurlwwwgoogleschemas
1条回答
网友
1楼 · 发布于 2024-05-19 12:23:50

您可以尝试定义一个包装模式-架构.xsd导入所需的所有模式,并将此模式与lxml一起使用,而不是其他模式中的每一个。在

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:import
    namespace="http://www.sitemaps.org/schemas/sitemap/0.9"
    schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"/>
  <xs:import
    namespace="http://www.google.com/schemas/sitemap-image/1.1"
    schemaLocation="http://www.google.com/schemas/sitemap-image/1.1/sitemap-image.xsd"/>
</xs:schema>

我没有python,但这在氧气中可以成功验证:

^{pr2}$

相关问题 更多 >