针对Google Images站点地图的两个XSD验证XML

时间:2011-04-18 22:34:10

标签: xml validation xsd

我有一个XML文件(使用Google的<image:image>扩展名的站点地图)我需要针对两个本地XSD文件进行验证,但验证失败,因为<url>不允许<image:image>作为一个孩子。完整的错误消息是

org.xml.sax.SAXParseException: 
cvc-complex-type.2.4.a: Invalid content was found starting with element 'image:image'.
One of '{"http://www.sitemaps.org/schemas/sitemap/0.9":lastmod, 
         "http://www.sitemaps.org/schemas/sitemap/0.9":changefreq, 
         "http://www.sitemaps.org/schemas/sitemap/0.9":priority}' 
is expected.

这是我正在尝试验证的站点地图XML:

<?xml version="1.0"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">
  <url>
    <loc>http://example.com/index.html</loc>
    <image:image>
      <image:loc>http://example.com/images/mysite.jpg</image:loc>
      <image:title>My Site's Logo</image:title>
      <image:caption>Logo for My Site by Andy Warhol (not really)</image:caption>
    </image:image>
  </url>
  ...
</urlset>

我正在使用sitemapsGoogle Images的标准XSD,但由于两者都没有引用另一个,我不知道如何使<image:image>成为<url>的有效子项}。

如果有帮助,这是执行验证的代码。

Source document = ...
StreamSource[] source = new StreamSource[] {
        new StreamSource(this.getClass().getResourceAsStream("sitemap.xsd"), "http://www.sitemaps.org/schemas/sitemap/0.9"),
        new StreamSource(this.getClass().getResourceAsStream("sitemap-image.xsd"), "http://www.google.com/schemas/sitemap-image/1.1")
    };
SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(source)
             .newValidator().validate(document);

closest SO question I could find需要预解析和拆分XML文件,因为要应用的架构因数据值而异。我的要求更简单,我希望更容易解决。

更新:我有一个旧架构,不允许该元素的任何其他子节点。 sitemaps.org已更新其XSD以添加

<xsd:any namespace="##other" minOccurs="0" maxOccurs="unbounded" processContents="strict"/>

2 个答案:

答案 0 :(得分:1)

实际上,站点地图架构允许该位置的任何元素,只要它来自另一个名称空间,并且只要有一个架构(因为“processContent”是严格的。但是,您的&lt; image&gt;数据无效,&lt; caption&gt;必须出现在&lt; title&gt;之前。

当我在Java 1.6上测试时,它会验证确定。

答案 1 :(得分:1)

我花了一些时间来弄清楚进行模式验证的语法(Google自己的示例实际上并未对XSD文件进行验证):

<urlset  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"
         xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
         xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">