【问题标题】:Understanding xml schemalocation了解 xml 架构位置
【发布时间】:2015-02-27 12:35:18
【问题描述】:

我正在尝试实现以下 xml 文件的 xmlns 定义的要点:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">   
</beans>

我没有得到这里指定的 schemaLocation。例如,为什么我应该将xmlns:mvc = "http://www.springframework.org/schema/mvc"http://www.springframework.org/schema/mvc 添加到schemaLocation 属性以在我的spring 配置文件中使用mvc:xxx_something_xxx

我只是想了解我每次开始创建spring-mvc应用程序时都在做什么,而不是在不了解的情况下从google复制粘贴它。

【问题讨论】:

    标签: java xml spring spring-mvc


    【解决方案1】:

    这是两个不同的东西:

    • xmlns:mvc="http://www.springframework.org/schema/mvc" 是一个声明,在这里你说“嘿,当我要在我的 XML 代码中使用“mvc”前缀时,我将使用这个命名空间中的元素和类型”;声明的命名空间应与所需架构中的 xmlns 属性匹配,以便可以识别它
    • schemaLocation="http://www.springframework.org/schema/mvc" 是一个模式位置,就像 java 中的类路径或 linux 中的路径一样,它是 XML 处理器可以找到 XSD 模式文件的源列表;您需要的架构应该位于此列表中,以便可以找到 XSD 文件

    如果没有声明,您不能引用不同于当前模式命名空间(在您的情况下为 xmlns="http://www.springframework.org/schema/beans")的命名空间中的元素和类型。

    如果没有架构位置,您将收到无法找到元素或类型的错误。

    【讨论】:

    • 所以,据我了解,当我们使用 mvc:xxx_smth_xxx 时,SAXParser 转到 schemaLocation 中指定的 URL 以获取 XSD 模式,然后调用验证。但是当我关闭互联网连接时它仍然可以工作,为什么?
    • 因为它当然有缓存,所以请考虑任何时候你想处理你的 applicationContext.xml 你从互联网上读取模式 - 这将非常糟糕
    【解决方案2】:

    xmlns 定义了一个命名空间。如果你想使用mvc:xxx,你必须定义mvc命名空间是什么。

    xsi:schemaLocation 定义 XSD(用于 XML 验证)的位置。

    如果我没记错的话,最新的不是强制性的,但如果你不设置它,那么你可能会使用无效的 XML 而不会注意到它。

    相关:

    【讨论】:

      猜你喜欢
      • 2016-11-08
      • 2011-09-02
      • 1970-01-01
      • 2016-03-22
      • 2010-10-06
      • 2014-10-15
      • 2019-08-11
      • 2011-09-27
      • 1970-01-01
      相关资源
      最近更新 更多