解析xml有SAX,Stax,dom等方式,那么spring中是如何解析xml文件的呢?

  1. Document doc = this.documentLoader.loadDocument(
  2. inputSource, getEntityResolver(), this.errorHandler, validationMode, isNamespaceAware());

spring中采用的DOM的方式,所要做的一切就是得到org.w3c.dom.Document对象

上面的documentLoader是DefaultDocumentLoader对象

  1. /*
  2. * Copyright 2002-2007 the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16.  
  17. package org.springframework.beans.factory.xml;
  18.  
  19. import javax.xml.parsers.DocumentBuilder;
  20. import javax.xml.parsers.DocumentBuilderFactory;
  21. import javax.xml.parsers.ParserConfigurationException;
  22.  
  23. import org.apache.commons.logging.Log;
  24. import org.apache.commons.logging.LogFactory;
  25. import org.springframework.util.xml.XmlValidationModeDetector;
  26. import org.w3c.dom.Document;
  27. import org.xml.sax.EntityResolver;
  28. import org.xml.sax.ErrorHandler;
  29. import org.xml.sax.InputSource;
  30.  
  31. /**
  32. * Spring's default {@link DocumentLoader} implementation.
  33. *
  34. * <p>Simply loads {@link Document documents} using the standard JAXP-configured
  35. * XML parser. If you want to change the {@link DocumentBuilder} that is used to
  36. * load documents, then one strategy is to define a corresponding Java system property
  37. * when starting your JVM. For example, to use the Oracle {@link DocumentBuilder},
  38. * you might start your application like as follows:
  39. *
  40. * <pre code="class">java -Djavax.xml.parsers.DocumentBuilderFactory=oracle.xml.jaxp.JXDocumentBuilderFactory MyMainClass</pre>
  41. *
  42. * @author Rob Harrop
  43. * @author Juergen Hoeller
  44. * @since 2.0
  45. */
  46. public class DefaultDocumentLoader implements DocumentLoader {
  47.  
  48. /**
  49. * JAXP attribute used to configure the schema language for validation.
  50. */
  51. private static final String SCHEMA_LANGUAGE_ATTRIBUTE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
  52.  
  53. /**
  54. * JAXP attribute value indicating the XSD schema language.
  55. */
  56. private static final String XSD_SCHEMA_LANGUAGE = "http://www.w3.org/2001/XMLSchema";
  57.  
  58. private static final Log logger = LogFactory.getLog(DefaultDocumentLoader.class);
  59.  
  60. /**
  61. * Load the {@link Document} at the supplied {@link InputSource} using the standard JAXP-configured
  62. * XML parser.
  63. */
  64. public Document loadDocument(InputSource inputSource, EntityResolver entityResolver,
  65. ErrorHandler errorHandler, int validationMode, boolean namespaceAware) throws Exception {
  66.  
  67. DocumentBuilderFactory factory = createDocumentBuilderFactory(validationMode, namespaceAware);
  68. if (logger.isDebugEnabled()) {
  69. logger.debug("Using JAXP provider [" + factory.getClass().getName() + "]");
  70. }
  71. DocumentBuilder builder = createDocumentBuilder(factory, entityResolver, errorHandler);
  72. return builder.parse(inputSource);
  73. }
  74.  
  75. /**
  76. * Create the {@link DocumentBuilderFactory} instance.
  77. * @param validationMode the type of validation: {@link XmlValidationModeDetector#VALIDATION_DTD DTD}
  78. * or {@link XmlValidationModeDetector#VALIDATION_XSD XSD})
  79. * @param namespaceAware whether the returned factory is to provide support for XML namespaces
  80. * @return the JAXP DocumentBuilderFactory
  81. * @throws ParserConfigurationException if we failed to build a proper DocumentBuilderFactory
  82. */
  83. protected DocumentBuilderFactory createDocumentBuilderFactory(int validationMode, boolean namespaceAware)
  84. throws ParserConfigurationException {
  85.  
  86. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  87. factory.setNamespaceAware(namespaceAware);
  88.  
  89. if (validationMode != XmlValidationModeDetector.VALIDATION_NONE) {
  90. factory.setValidating(true);
  91.  
  92. if (validationMode == XmlValidationModeDetector.VALIDATION_XSD) {
  93. // Enforce namespace aware for XSD...
  94. factory.setNamespaceAware(true);
  95. try {
  96. factory.setAttribute(SCHEMA_LANGUAGE_ATTRIBUTE, XSD_SCHEMA_LANGUAGE);
  97. }
  98. catch (IllegalArgumentException ex) {
  99. ParserConfigurationException pcex = new ParserConfigurationException(
  100. "Unable to validate using XSD: Your JAXP provider [" + factory +
  101. "] does not support XML Schema. Are you running on Java 1.4 with Apache Crimson? " +
  102. "Upgrade to Apache Xerces (or Java 1.5) for full XSD support.");
  103. pcex.initCause(ex);
  104. throw pcex;
  105. }
  106. }
  107. }
  108.  
  109. return factory;
  110. }
  111.  
  112. /**
  113. * Create a JAXP DocumentBuilder that this bean definition reader
  114. * will use for parsing XML documents. Can be overridden in subclasses,
  115. * adding further initialization of the builder.
  116. * @param factory the JAXP DocumentBuilderFactory that the DocumentBuilder
  117. * should be created with
  118. * @param entityResolver the SAX EntityResolver to use
  119. * @param errorHandler the SAX ErrorHandler to use
  120. * @return the JAXP DocumentBuilder
  121. * @throws ParserConfigurationException if thrown by JAXP methods
  122. */
  123. protected DocumentBuilder createDocumentBuilder(
  124. DocumentBuilderFactory factory, EntityResolver entityResolver, ErrorHandler errorHandler)
  125. throws ParserConfigurationException {
  126.  
  127. DocumentBuilder docBuilder = factory.newDocumentBuilder();
  128. if (entityResolver != null) {
  129. docBuilder.setEntityResolver(entityResolver);
  130. }
  131. if (errorHandler != null) {
  132. docBuilder.setErrorHandler(errorHandler);
  133. }
  134. return docBuilder;
  135. }
  136.  
  137. }

loadDocument中有一个参数entityResolver,类型是EntityResolver,这也没有什么,DocumentBuilder本来就可以设置setEntityResolver,那么现在这个entityResolver是什么对象呢?是

  1. DelegatingEntityResolver
  1. /*
  2. * Copyright 2002-2012 the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16.  
  17. package org.springframework.beans.factory.xml;
  18.  
  19. import java.io.IOException;
  20.  
  21. import org.springframework.util.Assert;
  22. import org.xml.sax.EntityResolver;
  23. import org.xml.sax.InputSource;
  24. import org.xml.sax.SAXException;
  25.  
  26. /**
  27. * {@link EntityResolver} implementation that delegates to a {@link BeansDtdResolver}
  28. * and a {@link PluggableSchemaResolver} for DTDs and XML schemas, respectively.
  29. *
  30. * @author Rob Harrop
  31. * @author Juergen Hoeller
  32. * @author Rick Evans
  33. * @since 2.0
  34. * @see BeansDtdResolver
  35. * @see PluggableSchemaResolver
  36. */
  37. public class DelegatingEntityResolver implements EntityResolver {
  38.  
  39. /** Suffix for DTD files */
  40. public static final String DTD_SUFFIX = ".dtd";
  41.  
  42. /** Suffix for schema definition files */
  43. public static final String XSD_SUFFIX = ".xsd";
  44.  
  45. private final EntityResolver dtdResolver;
  46.  
  47. private final EntityResolver schemaResolver;
  48.  
  49. /**
  50. * Create a new DelegatingEntityResolver that delegates to
  51. * a default {@link BeansDtdResolver} and a default {@link PluggableSchemaResolver}.
  52. * <p>Configures the {@link PluggableSchemaResolver} with the supplied
  53. * {@link ClassLoader}.
  54. * @param classLoader the ClassLoader to use for loading
  55. * (can be {@code null}) to use the default ClassLoader)
  56. */
  57. public DelegatingEntityResolver(ClassLoader classLoader) {
  58. this.dtdResolver = new BeansDtdResolver();
  59. this.schemaResolver = new PluggableSchemaResolver(classLoader);
  60. }
  61.  
  62. /**
  63. * Create a new DelegatingEntityResolver that delegates to
  64. * the given {@link EntityResolver EntityResolvers}.
  65. * @param dtdResolver the EntityResolver to resolve DTDs with
  66. * @param schemaResolver the EntityResolver to resolve XML schemas with
  67. */
  68. public DelegatingEntityResolver(EntityResolver dtdResolver, EntityResolver schemaResolver) {
  69. Assert.notNull(dtdResolver, "'dtdResolver' is required");
  70. Assert.notNull(schemaResolver, "'schemaResolver' is required");
  71. this.dtdResolver = dtdResolver;
  72. this.schemaResolver = schemaResolver;
  73. }
  74.  
  75. public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
  76. if (systemId != null) {
  77. if (systemId.endsWith(DTD_SUFFIX)) {
  78. return this.dtdResolver.resolveEntity(publicId, systemId);
  79. }
  80. else if (systemId.endsWith(XSD_SUFFIX)) {
  81. return this.schemaResolver.resolveEntity(publicId, systemId);
  82. }
  83. }
  84. return null;
  85. }
  86.  
  87. @Override
  88. public String toString() {
  89. return "EntityResolver delegating " + XSD_SUFFIX + " to " + this.schemaResolver +
  90. " and " + DTD_SUFFIX + " to " + this.dtdResolver;
  91. }
  92.  
  93. }

在DocumentBuilder调用parse方法的时候会调用EntityResolver(这里是DelegatingEntityResolver)的resolveEntity方法:

  1. public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
  2. if (systemId != null) {
  3. if (systemId.endsWith(DTD_SUFFIX)) {
  4. return this.dtdResolver.resolveEntity(publicId, systemId);
  5. }
  6. else if (systemId.endsWith(XSD_SUFFIX)) {
  7. return this.schemaResolver.resolveEntity(publicId, systemId);
  8. }
  9. }
  10. return null;
  11. }

请注意resolveEntity方法会根据systemId来返回不同的对象,systemId即是xsi:schemaLocation种的值

  1. /*
  2. * Copyright 2002-2012 the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16.  
  17. package org.springframework.beans.factory.xml;
  18.  
  19. import java.io.FileNotFoundException;
  20. import java.io.IOException;
  21. import java.util.Map;
  22. import java.util.Properties;
  23. import java.util.concurrent.ConcurrentHashMap;
  24.  
  25. import org.apache.commons.logging.Log;
  26. import org.apache.commons.logging.LogFactory;
  27. import org.springframework.core.io.ClassPathResource;
  28. import org.springframework.core.io.Resource;
  29. import org.springframework.core.io.support.PropertiesLoaderUtils;
  30. import org.springframework.util.Assert;
  31. import org.springframework.util.CollectionUtils;
  32. import org.xml.sax.EntityResolver;
  33. import org.xml.sax.InputSource;
  34.  
  35. /**
  36. * {@link EntityResolver} implementation that attempts to resolve schema URLs into
  37. * local {@link ClassPathResource classpath resources} using a set of mappings files.
  38. *
  39. * <p>By default, this class will look for mapping files in the classpath using the pattern:
  40. * {@code META-INF/spring.schemas} allowing for multiple files to exist on the
  41. * classpath at any one time.
  42. *
  43. * The format of {@code META-INF/spring.schemas} is a properties
  44. * file where each line should be of the form {@code systemId=schema-location}
  45. * where {@code schema-location} should also be a schema file in the classpath.
  46. * Since systemId is commonly a URL, one must be careful to escape any ':' characters
  47. * which are treated as delimiters in properties files.
  48. *
  49. * <p>The pattern for the mapping files can be overidden using the
  50. * {@link #PluggableSchemaResolver(ClassLoader, String)} constructor
  51. *
  52. * @author Rob Harrop
  53. * @author Juergen Hoeller
  54. * @since 2.0
  55. */
  56. public class PluggableSchemaResolver implements EntityResolver {
  57.  
  58. /**
  59. * The location of the file that defines schema mappings.
  60. * Can be present in multiple JAR files.
  61. */
  62. public static final String DEFAULT_SCHEMA_MAPPINGS_LOCATION = "META-INF/spring.schemas";
  63.  
  64. private static final Log logger = LogFactory.getLog(PluggableSchemaResolver.class);
  65.  
  66. private final ClassLoader classLoader;
  67.  
  68. private final String schemaMappingsLocation;
  69.  
  70. /** Stores the mapping of schema URL -> local schema path */
  71. private volatile Map<String, String> schemaMappings;
  72.  
  73. /**
  74. * Loads the schema URL -> schema file location mappings using the default
  75. * mapping file pattern "META-INF/spring.schemas".
  76. * @param classLoader the ClassLoader to use for loading
  77. * (can be {@code null}) to use the default ClassLoader)
  78. * @see PropertiesLoaderUtils#loadAllProperties(String, ClassLoader)
  79. */
  80. public PluggableSchemaResolver(ClassLoader classLoader) {
  81. this.classLoader = classLoader;
  82. this.schemaMappingsLocation = DEFAULT_SCHEMA_MAPPINGS_LOCATION;
  83. }
  84.  
  85. /**
  86. * Loads the schema URL -> schema file location mappings using the given
  87. * mapping file pattern.
  88. * @param classLoader the ClassLoader to use for loading
  89. * (can be {@code null}) to use the default ClassLoader)
  90. * @param schemaMappingsLocation the location of the file that defines schema mappings
  91. * (must not be empty)
  92. * @see PropertiesLoaderUtils#loadAllProperties(String, ClassLoader)
  93. */
  94. public PluggableSchemaResolver(ClassLoader classLoader, String schemaMappingsLocation) {
  95. Assert.hasText(schemaMappingsLocation, "'schemaMappingsLocation' must not be empty");
  96. this.classLoader = classLoader;
  97. this.schemaMappingsLocation = schemaMappingsLocation;
  98. }
  99.  
  100. public InputSource resolveEntity(String publicId, String systemId) throws IOException {
  101. if (logger.isTraceEnabled()) {
  102. logger.trace("Trying to resolve XML entity with public id [" + publicId +
  103. "] and system id [" + systemId + "]");
  104. }
  105.  
  106. if (systemId != null) {
  107. String resourceLocation = getSchemaMappings().get(systemId);
  108. if (resourceLocation != null) {
  109. Resource resource = new ClassPathResource(resourceLocation, this.classLoader);
  110. try {
  111. InputSource source = new InputSource(resource.getInputStream());
  112. source.setPublicId(publicId);
  113. source.setSystemId(systemId);
  114. if (logger.isDebugEnabled()) {
  115. logger.debug("Found XML schema [" + systemId + "] in classpath: " + resourceLocation);
  116. }
  117. return source;
  118. }
  119. catch (FileNotFoundException ex) {
  120. if (logger.isDebugEnabled()) {
  121. logger.debug("Couldn't find XML schema [" + systemId + "]: " + resource, ex);
  122. }
  123. }
  124. }
  125. }
  126. return null;
  127. }
  128.  
  129. /**
  130. * Load the specified schema mappings lazily.
  131. */
  132. private Map<String, String> getSchemaMappings() {
  133. if (this.schemaMappings == null) {
  134. synchronized (this) {
  135. if (this.schemaMappings == null) {
  136. if (logger.isDebugEnabled()) {
  137. logger.debug("Loading schema mappings from [" + this.schemaMappingsLocation + "]");
  138. }
  139. try {
  140. Properties mappings =
  141. PropertiesLoaderUtils.loadAllProperties(this.schemaMappingsLocation, this.classLoader);
  142. if (logger.isDebugEnabled()) {
  143. logger.debug("Loaded schema mappings: " + mappings);
  144. }
  145. Map<String, String> schemaMappings = new ConcurrentHashMap<String, String>(mappings.size());
  146. CollectionUtils.mergePropertiesIntoMap(mappings, schemaMappings);
  147. this.schemaMappings = schemaMappings;
  148. }
  149. catch (IOException ex) {
  150. throw new IllegalStateException(
  151. "Unable to load schema mappings from location [" + this.schemaMappingsLocation + "]", ex);
  152. }
  153. }
  154. }
  155. }
  156. return this.schemaMappings;
  157. }
  158.  
  159. @Override
  160. public String toString() {
  161. return "EntityResolver using mappings " + getSchemaMappings();
  162. }
  163.  
  164. }
  1. /*
  2. * Copyright 2002-2012 the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16.  
  17. package org.springframework.beans.factory.xml;
  18.  
  19. import java.io.IOException;
  20. import java.util.Arrays;
  21.  
  22. import org.apache.commons.logging.Log;
  23. import org.apache.commons.logging.LogFactory;
  24. import org.springframework.core.io.ClassPathResource;
  25. import org.springframework.core.io.Resource;
  26. import org.xml.sax.EntityResolver;
  27. import org.xml.sax.InputSource;
  28.  
  29. /**
  30. * EntityResolver implementation for the Spring beans DTD,
  31. * to load the DTD from the Spring class path (or JAR file).
  32. *
  33. * <p>Fetches "spring-beans-2.0.dtd" from the class path resource
  34. * "/org/springframework/beans/factory/xml/spring-beans-2.0.dtd",
  35. * no matter whether specified as some local URL that includes "spring-beans"
  36. * in the DTD name or as "http://www.springframework.org/dtd/spring-beans-2.0.dtd".
  37. *
  38. * @author Juergen Hoeller
  39. * @author Colin Sampaleanu
  40. * @since 04.06.2003
  41. * @see ResourceEntityResolver
  42. */
  43. public class BeansDtdResolver implements EntityResolver {
  44.  
  45. private static final String DTD_EXTENSION = ".dtd";
  46.  
  47. private static final String[] DTD_NAMES = {"spring-beans-2.0", "spring-beans"};
  48.  
  49. private static final Log logger = LogFactory.getLog(BeansDtdResolver.class);
  50.  
  51. public InputSource resolveEntity(String publicId, String systemId) throws IOException {
  52. if (logger.isTraceEnabled()) {
  53. logger.trace("Trying to resolve XML entity with public ID [" + publicId +
  54. "] and system ID [" + systemId + "]");
  55. }
  56. if (systemId != null && systemId.endsWith(DTD_EXTENSION)) {
  57. int lastPathSeparator = systemId.lastIndexOf("/");
  58. for (String DTD_NAME : DTD_NAMES) {
  59. int dtdNameStart = systemId.indexOf(DTD_NAME);
  60. if (dtdNameStart > lastPathSeparator) {
  61. String dtdFile = systemId.substring(dtdNameStart);
  62. if (logger.isTraceEnabled()) {
  63. logger.trace("Trying to locate [" + dtdFile + "] in Spring jar");
  64. }
  65. try {
  66. Resource resource = new ClassPathResource(dtdFile, getClass());
  67. InputSource source = new InputSource(resource.getInputStream());
  68. source.setPublicId(publicId);
  69. source.setSystemId(systemId);
  70. if (logger.isDebugEnabled()) {
  71. logger.debug("Found beans DTD [" + systemId + "] in classpath: " + dtdFile);
  72. }
  73. return source;
  74. }
  75. catch (IOException ex) {
  76. if (logger.isDebugEnabled()) {
  77. logger.debug("Could not resolve beans DTD [" + systemId + "]: not found in class path", ex);
  78. }
  79. }
  80.  
  81. }
  82. }
  83. }
  84.  
  85. // Use the default behavior -> download from website or wherever.
  86. return null;
  87. }
  88.  
  89. @Override
  90. public String toString() {
  91. return "EntityResolver for DTDs " + Arrays.toString(DTD_NAMES);
  92. }
  93.  
  94. }

在PluggableSchemaResolver类中会去加载META-INF/spring.schemas

  1. http\://www.springframework.org/schema/beans/spring-beans-2.0.xsd=org/springframework/beans/factory/xml/spring-beans-2.0.xsd
  2. http\://www.springframework.org/schema/beans/spring-beans-2.5.xsd=org/springframework/beans/factory/xml/spring-beans-2.5.xsd
  3. http\://www.springframework.org/schema/beans/spring-beans-3.0.xsd=org/springframework/beans/factory/xml/spring-beans-3.0.xsd
  4. http\://www.springframework.org/schema/beans/spring-beans-3.1.xsd=org/springframework/beans/factory/xml/spring-beans-3.1.xsd
  5. http\://www.springframework.org/schema/beans/spring-beans-3.2.xsd=org/springframework/beans/factory/xml/spring-beans-3.2.xsd
  6. http\://www.springframework.org/schema/beans/spring-beans.xsd=org/springframework/beans/factory/xml/spring-beans-3.2.xsd
  7. http\://www.springframework.org/schema/tool/spring-tool-2.0.xsd=org/springframework/beans/factory/xml/spring-tool-2.0.xsd
  8. http\://www.springframework.org/schema/tool/spring-tool-2.5.xsd=org/springframework/beans/factory/xml/spring-tool-2.5.xsd
  9. http\://www.springframework.org/schema/tool/spring-tool-3.0.xsd=org/springframework/beans/factory/xml/spring-tool-3.0.xsd
  10. http\://www.springframework.org/schema/tool/spring-tool-3.1.xsd=org/springframework/beans/factory/xml/spring-tool-3.1.xsd
  11. http\://www.springframework.org/schema/tool/spring-tool-3.2.xsd=org/springframework/beans/factory/xml/spring-tool-3.2.xsd
  12. http\://www.springframework.org/schema/tool/spring-tool.xsd=org/springframework/beans/factory/xml/spring-tool-3.2.xsd
  13. http\://www.springframework.org/schema/util/spring-util-2.0.xsd=org/springframework/beans/factory/xml/spring-util-2.0.xsd
  14. http\://www.springframework.org/schema/util/spring-util-2.5.xsd=org/springframework/beans/factory/xml/spring-util-2.5.xsd
  15. http\://www.springframework.org/schema/util/spring-util-3.0.xsd=org/springframework/beans/factory/xml/spring-util-3.0.xsd
  16. http\://www.springframework.org/schema/util/spring-util-3.1.xsd=org/springframework/beans/factory/xml/spring-util-3.1.xsd
  17. http\://www.springframework.org/schema/util/spring-util-3.2.xsd=org/springframework/beans/factory/xml/spring-util-3.2.xsd
  18. http\://www.springframework.org/schema/util/spring-util.xsd=org/springframework/beans/factory/xml/spring-util-3.2.xsd

然后根据systemId去对象的位置获取对应xsd文件

为什么要设置EntityResolver呢?如果xml文件不符合xsd文件,则解析时候会报错,spring中对这种错误的情况只是报异常而已

  1. /*
  2. * Copyright 2002-2012 the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16.  
  17. package org.springframework.util.xml;
  18.  
  19. import org.apache.commons.logging.Log;
  20. import org.xml.sax.ErrorHandler;
  21. import org.xml.sax.SAXException;
  22. import org.xml.sax.SAXParseException;
  23.  
  24. /**
  25. * Simple {@code org.xml.sax.ErrorHandler} implementation:
  26. * logs warnings using the given Commons Logging logger instance,
  27. * and rethrows errors to discontinue the XML transformation.
  28. *
  29. * @author Juergen Hoeller
  30. * @since 1.2
  31. */
  32. public class SimpleSaxErrorHandler implements ErrorHandler {
  33.  
  34. private final Log logger;
  35.  
  36. /**
  37. * Create a new SimpleSaxErrorHandler for the given
  38. * Commons Logging logger instance.
  39. */
  40. public SimpleSaxErrorHandler(Log logger) {
  41. this.logger = logger;
  42. }
  43.  
  44. public void warning(SAXParseException ex) throws SAXException {
  45. logger.warn("Ignored XML validation warning", ex);
  46. }
  47.  
  48. public void error(SAXParseException ex) throws SAXException {
  49. throw ex;
  50. }
  51.  
  52. public void fatalError(SAXParseException ex) throws SAXException {
  53. throw ex;
  54. }
  55.  
  56. }

spring中解析xml的更多相关文章

  1. 6.2 dubbo在spring中自定义xml标签源码解析

    在6.1 如何在spring中自定义xml标签中我们看到了在spring中自定义xml标签的方式.dubbo也是这样来实现的. 一 META_INF/dubbo.xsd 比较长,只列出<dubb ...

  2. 6.1 如何在spring中自定义xml标签

    dubbo自定义了很多xml标签,例如<dubbo:application>,那么这些自定义标签是怎么与spring结合起来的呢?我们先看一个简单的例子. 一 编写模型类 package ...

  3. 用 ElementTree 在 Python 中解析 XML

    用 ElementTree 在 Python 中解析 XML 原文: http://eli.thegreenplace.net/2012/03/15/processing-xml-in-python- ...

  4. iOS中解析 XML / JSON

    JSON数据格式 1. 概述: JSON (JavaScript Object Notation) 是⼀一种轻量级的数据交换格式 基于⽂文本格式,易于⼈人阅读和编写,同时也易于机器解析和⽣生成. 2. ...

  5. [置顶] Android学习系列-Android中解析xml(7)

    Android学习系列-Android中解析xml(7) 一,概述 1,一个是DOM,它是生成一个树,有了树以后你搜索.查找都可以做. 2,另一种是基于流的,就是解析器从头到尾解析一遍xml文件.   ...

  6. web.xml中配置Spring中applicationContext.xml的方式

    2011-11-08 16:29 web.xml中配置Spring中applicationContext.xml的方式 使用web.xml方式加载Spring时,获取Spring applicatio ...

  7. Delphi中解析Xml的控件-SimDesign NativeXml

    Delphi中解析Xml的控件-SimDesign NativeXml 正在学习,感觉应用很方便.无源代码的版本还是免费的. SimDesign.NativeXml是一个delphi和bcb的XML控 ...

  8. Android中解析XML格式数据的方法

    XML介绍:Extensible Markup Language,即可扩展标记语言 一.概述 Android中解析XML格式数据大致有三种方法: SAX DOM PULL 二.详解 2.1 SAX S ...

  9. ssh整合思想初步 struts2与Spring的整合 struts2-spring-plugin-2.3.4.1.jar下载地址 自动加载Spring中的XML配置文件 Struts2下载地址

    首先需要JAR包 Spring整合Structs2的JAR包 struts2-spring-plugin-2.3.4.1.jar 下载地址 链接: https://pan.baidu.com/s/1o ...

随机推荐

  1. while loading persisted sessions 异常解决方法

    一直用tomcat一段时间都正常无事,最近一次启动tomcat就发生以下异常: 严重: IOException while loading persisted sessions: java.io.EO ...

  2. c#yield,IEnumerable,IEnumerator

    foreach 在编译成IL后,实际代码如下: 即:foreach实际上是先调用可枚举对象的GetEnumerator方法,得到一个Enumerator对象,然后对Enumerator进行while循 ...

  3. asp.net web api内部培训资料

    最近在公司进行了一次asp.net web api的分享吧,不算是培训. 可能大家有些人对Web API的推出目的还不是很了解,可以看看微软官方的定义,其实是为了提供一个好的REST Service方 ...

  4. 【转】.Net中通过反射技术的应用----插件程序的开发入门

    转自:http://www.cnblogs.com/winloa/archive/2012/03/25/2416355.html .Net中通过反射技术的应用----插件程序的开发入门 再开始之前,先 ...

  5. 时区之痒 - 从手机GPS模块获取的时间,真的是北京时间么?

    去年互联网地图行业开始引入众包模式,国内比较大的地图商,比如四维图新.高德地图.百度地图纷纷开始推出UGC应用,众包给用户采集门址.公交站等信息,并按照工作量给与采集者一定的回报.我曾经玩过某德推出的 ...

  6. 网上流行的add(2)(3)(4)

    网上有很多其他的各样的算法.其实这题就可以用javascript属性arguments.callee来实现,代码如下: function add(x){ var result=0; return fu ...

  7. createjs 下雪 实例

    demo:  http://output.jsbin.com/davixatona <!DOCTYPE html> <html> <head> <meta c ...

  8. C#程序中:如何删除xml文件中的节点、元素。

    C#中动态的清理xml文件中的垃圾信息是程序员必会的哦.这就像数据库一样,不会清理数据怎么可以呢?其实xml文件就可以用作一个小的数据库,存储一些简单的信息.所以,用C#程序实现xml文件的增.删.改 ...

  9. 1、Python django 框架下的word Excel TXT Image 等文件的上传

    1.文件上传(input标签) (1)html代码(form表单用post方法提交) <input class="btn btn-primary col-md-1" styl ...

  10. http知识累积

    1. http头 Host, Host请求报头域主要用于指定被请求资源的Internet主机和端口号,它通常从HTTP URL中提取出来的. 如果有黑客劫持了用户的请求,篡改了Host的内容,当请求到 ...