`

Spring读取xml文件[schema/dtd]

    博客分类:
  • XML
 
阅读更多
主测试类如下:
说明
  • 使用了ErrorHandler,主要是把异常信息接到我们常用的日志信息中
  • 使用了EntityResolver,实体解析类,主要解决xml中publicId对应的schema/dtd.
  • 设置了DocumentBuilderFactory,主要设置名称空间,是否验证schema/dtd
  • 建立META-INF/myschema.schemas,指定命名空间对应的xsd/dtd实际的路径[本地或网络]

package org.frame.base.xml.jdk.bk;

import java.io.IOException;
import java.io.StringReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.frame.base.xml.jdk.ContactName;
import org.frame.base.xml.jdk.MaySimpleSaxErrorHandler;
import org.frame.base.xml.jdk.MyPluggableSchemaResolver;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 * xml reader
 * 
 * this example is from spring code.
 * @see spring XmlBeanDefinitionReader
 *
 * @author ycl
 * @version 1.0 2012-12-11 下午2:06:55
 * @since 1.0
 *
 */
public class TestDocumentBuilderFactory {
	
	protected final static Log logger = LogFactory.getLog(TestDocumentBuilderFactory.class);

	public static void main(String[] args) { 
		
		//set jaxp debug
		System.setProperty("jaxp.debug","1");  
		DocumentBuilderFactory builderFactory = DocumentBuilderFactory
				.newInstance();
		
		//设置使用命名空间
		builderFactory.setNamespaceAware(true);
		builderFactory.setValidating(true);
		builderFactory.setIgnoringComments(true); 
		builderFactory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
		//如果使用xsd,一船需要设置schemaLanguage的schema版本.
		
		ErrorHandler errorHandler = new MaySimpleSaxErrorHandler(logger);
		//异常处理类
		EntityResolver entityResolver = new MyPluggableSchemaResolver(TestDocumentBuilderFactory.class.getClassLoader());
		//实体分解类
		
		Document document = parse(builderFactory,getInputSource(),entityResolver,errorHandler); 
		 
		print(document);
		
	}
	
	private static void print(Document document){
		Element root = document.getDocumentElement();
		
		List<ContactName> contactNameList = new ArrayList<ContactName>();

		ContactName contactItem;

		// 子元素列表
		NodeList nodes = root.getChildNodes();
		
		/**
		 * code this is so tied.
		 */
		for (int i = 0; i < nodes.getLength(); i++) {
			Node node = nodes.item(i); 
			if (node instanceof Element) {
				// a child element to process
				Element child = (Element) node; 
				String width = child.getAttribute("width");
				contactItem = new ContactName();
				contactItem.setWidth(width);
				NodeList itemSub = node.getChildNodes();
				for (int j = 0; j < itemSub.getLength(); j++) {
					Node itemSubNode = itemSub.item(j); 
					if (itemSubNode instanceof Element) {
						if(((Element) itemSubNode).getTagName().equals("uic")){
							contactItem.setUid(itemSubNode.getTextContent());
						}else if(((Element) itemSubNode).getTagName().equals("fullName")){
							contactItem.setFullName(itemSubNode.getTextContent());
						}
					}
				}
				contactNameList.add(contactItem);
			}
		}
		System.out.println(contactNameList);
	}
	
	private static InputSource getInputSource(){
		StringBuffer xml = new StringBuffer(
				"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); 
		xml.append("<contact xmlns=\"http://www.ycl.com/schema/schema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.ycl.com/schema/schema  http://www.ycl.com/schema/schema.xsd\" >"); 
		xml.append("<!--ycl is good -->");
		xml.append("<item width=\"10\">");
		xml.append("<uic>1</uic>");
		xml.append("<fullName>ycl1</fullName>");
		xml.append("</item>");

		xml.append("<item width=\"11\">");
		xml.append("<uic>1 <![CDATA[06:00 Vesti<br>06:05 Jutarnji]]> 2</uic>");
		xml.append("<fullName>ycl2</fullName>");
		xml.append("</item>");

		xml.append("</contact>"); 

		InputSource is = new InputSource(new StringReader(xml.toString()));
		return is;
	}
	
	private static Document parse(DocumentBuilderFactory builderFactory,InputSource is,EntityResolver entityResolver, ErrorHandler errorHandler) { 
		DocumentBuilder builder = null;

		Document document = null;
		try {
			builder = builderFactory.newDocumentBuilder();
			if (entityResolver != null) {
				builder.setEntityResolver(entityResolver);
			}
			if (errorHandler != null) {
				builder.setErrorHandler(errorHandler);
			}
			document = builder.parse(is);
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return document;
	} 
}



package org.frame.base.xml.jdk;

import org.apache.commons.logging.Log;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class MaySimpleSaxErrorHandler implements ErrorHandler {

	private final Log logger;


	/**
	 * Create a new SimpleSaxErrorHandler for the given
	 * Commons Logging logger instance.
	 */
	public MaySimpleSaxErrorHandler(Log logger) {
		this.logger = logger;
	}


	public void warning(SAXParseException ex) throws SAXException {
		logger.warn("Ignored XML validation warning", ex);
	}

	public void error(SAXParseException ex) throws SAXException {
		throw ex;
	}

	public void fatalError(SAXParseException ex) throws SAXException {
		throw ex;
	}

}



package org.frame.base.xml.jdk;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.xml.PluggableSchemaResolver;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class MyPluggableSchemaResolver implements EntityResolver {
	
	/**
	 * The location of the file that defines schema mappings.
	 * Can be present in multiple JAR files.
	 */
	public static final String DEFAULT_SCHEMA_MAPPINGS_LOCATION = "META-INF/myschema.schemas";

	private static final Log logger = LogFactory.getLog(PluggableSchemaResolver.class);

	private final ClassLoader classLoader;

	private final String schemaMappingsLocation;

	/** Stores the mapping of schema URL -> local schema path */
	private volatile Map<String, String> schemaMappings;


	/**
	 * Loads the schema URL -> schema file location mappings using the default
	 * mapping file pattern "META-INF/spring.schemas".
	 * @param classLoader the ClassLoader to use for loading
	 * (can be <code>null</code>) to use the default ClassLoader)
	 * @see PropertiesLoaderUtils#loadAllProperties(String, ClassLoader)
	 */
	public MyPluggableSchemaResolver(ClassLoader classLoader) {
		this.classLoader = classLoader;
		this.schemaMappingsLocation = DEFAULT_SCHEMA_MAPPINGS_LOCATION;
	}

	/**
	 * Loads the schema URL -> schema file location mappings using the given
	 * mapping file pattern.
	 * @param classLoader the ClassLoader to use for loading
	 * (can be <code>null</code>) to use the default ClassLoader)
	 * @param schemaMappingsLocation the location of the file that defines schema mappings
	 * (must not be empty)
	 * @see PropertiesLoaderUtils#loadAllProperties(String, ClassLoader)
	 */
	public MyPluggableSchemaResolver(ClassLoader classLoader, String schemaMappingsLocation) {
		Assert.hasText(schemaMappingsLocation, "'schemaMappingsLocation' must not be empty");
		this.classLoader = classLoader;
		this.schemaMappingsLocation = schemaMappingsLocation;
	}

	public InputSource resolveEntity(String publicId, String systemId) throws IOException {
		if (logger.isTraceEnabled()) {
			logger.trace("Trying to resolve XML entity with public id [" + publicId +
					"] and system id [" + systemId + "]");
		}

		if (systemId != null) {
			String resourceLocation = getSchemaMappings().get(systemId);
			if (resourceLocation != null) {
				Resource resource = new ClassPathResource(resourceLocation, this.classLoader);
				try {
					InputSource source = new InputSource(resource.getInputStream());
					source.setPublicId(publicId);
					source.setSystemId(systemId);
					if (logger.isDebugEnabled()) {
						logger.debug("Found XML schema [" + systemId + "] in classpath: " + resourceLocation);
					}
					return source;
				}
				catch (FileNotFoundException ex) {
					if (logger.isDebugEnabled()) {
						logger.debug("Couldn't find XML schema [" + systemId + "]: " + resource, ex);
					}
				}
			}
		}
		return null;
	}

	/**
	 * Load the specified schema mappings lazily.
	 */
	private Map<String, String> getSchemaMappings() {
		if (this.schemaMappings == null) {
			synchronized (this) {
				if (this.schemaMappings == null) {
					if (logger.isDebugEnabled()) {
						logger.debug("Loading schema mappings from [" + this.schemaMappingsLocation + "]");
					}
					try {
						Properties mappings =
								PropertiesLoaderUtils.loadAllProperties(this.schemaMappingsLocation, this.classLoader);
						if (logger.isDebugEnabled()) {
							logger.debug("Loaded schema mappings: " + mappings);
						}
						Map<String, String> schemaMappings = new ConcurrentHashMap<String, String>();
						CollectionUtils.mergePropertiesIntoMap(mappings, schemaMappings);
						this.schemaMappings = schemaMappings;
					}
					catch (IOException ex) {
						throw new IllegalStateException(
								"Unable to load schema mappings from location [" + this.schemaMappingsLocation + "]", ex);
					}
				}
			}
		}
		return this.schemaMappings;
	}


	@Override
	public String toString() {
		return "EntityResolver using mappings " + getSchemaMappings();
	}

}



META-INF/myschema.schemas
http\://www.ycl.com/schema/schema.xsd=org/frame/base/xml/jdk/schema.xsd


myschema.schemas
<?xml version="1.0" encoding="utf-8"?>
<xsd:schema elementFormDefault="qualified" attributeFormDefault="unqualified"
	xmlns="http://www.ycl.com/schema/schema"  
	targetNamespace="http://www.ycl.com/schema/schema" 
	xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
	<xsd:element name="contact">
		<xsd:complexType>
			<xsd:sequence> 
				<xsd:element name="item" maxOccurs="unbounded">
					<xsd:complexType> 
						<xsd:sequence>
							<xsd:element name="uic">
								<xsd:simpleType>
									<xsd:restriction base="xsd:string">
										<xsd:minLength value="1" />
										<xsd:maxLength value="250" />
									</xsd:restriction>
								</xsd:simpleType>
							</xsd:element>
							<xsd:element name="fullName">
								<xsd:simpleType>
									<xsd:restriction base="xsd:string">
										<xsd:minLength value="1" />
										<xsd:maxLength value="250" />
									</xsd:restriction>
								</xsd:simpleType>
							</xsd:element> 
						</xsd:sequence>  
						<xsd:attribute name="width" type="xsd:string"></xsd:attribute>
					</xsd:complexType>
				</xsd:element>
			</xsd:sequence>
		</xsd:complexType>
	</xsd:element>
</xsd:schema>
分享到:
评论

相关推荐

    Spring各版本的xml约束

    综上所述,DTD和Schema在Spring及Mybatis中起到了验证和规范XML配置文件的作用,保证了代码的稳定性和可维护性。了解并熟练掌握这些XML约束,对于理解和使用这两个框架至关重要。通过学习和实践,开发者可以更好地...

    ssm框架整合

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop=...

    Java中spring读取配置文件的几种方法示例

    DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"&gt; &lt;bean id="helloBean" class="springdemo.HelloBean"&gt; &lt;value&gt;Hello!chb!&lt;/value&gt; &lt;/property&gt; &lt;/...

    Spring MVC 入门实例

    4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 6 http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"&gt; 7 8 9 &lt;param-name&gt;...

    xml文件代码

    在实际应用中,XML常用于配置文件,如Web应用的Spring框架就大量使用XML配置。此外,它也用于Web服务之间的数据交换,如SOAP(Simple Object Access Protocol)消息就是基于XML的。 总结来说,XML是一种重要的数据...

    XML读取以及解析

    - **SAX解析**:Simple API for XML,逐行读取XML,事件驱动。当遇到元素开始、结束、属性等时触发回调函数。适合处理大型XML文件,内存占用低,但操作相对复杂。 - **PULL解析**:类似于SAX,也采用事件驱动,但...

    xml文件解析

    SAX(Simple API for XML)是一种事件驱动的解析方式,它不创建整个文档树,而是逐行读取XML,遇到开始标签、结束标签等事件时触发回调函数。SAX解析适用于大文件或内存有限的情况,因为它占用的资源较少。 四、...

    创建XML文件.rar

    XML常用于Web服务中的数据交换(如SOAP),配置文件(如Spring框架的配置),以及数据库存储(如MongoDB)。此外,它也被用作电子邮件标准(如RFC822的替代,即MIME)的一部分。 10. XML解析器: 各种编程语言都有...

    ibatis与spring整合

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"&gt; ...

    spring oracle blob

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"&gt; &lt;!-- 事务...

    struts2.0spring2.5hibernate3.0框架整合步骤

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"&gt; &lt;!-- 定义bean.....

    day38 15-Spring的配置文件引入的问题

    3. **命名空间问题**:Spring配置文件可能包含特定的命名空间,如`http://www.springframework.org/schema/beans`,这些命名空间需要正确的DTD或XSD来解析。 4. **Bean定义错误**:Bean的ID必须是唯一的,否则...

    java xml realworld problem

    - SAX(简单API for XML)解析器:事件驱动型,逐行读取XML文件,适用于大文件处理。如javax.xml.parsers.SAXParserFactory和SAXParser。 - StAX(Streaming API for XML):流式解析,允许前后移动,平衡性能和...

    操作XML工程文件

    4. XML Schema(XSD)和DTD(Document Type Definition):用于定义XML文档的结构和约束,确保数据的准确性和一致性。 5. 编写XML工具:许多IDE(集成开发环境)如Eclipse、IntelliJ IDEA提供了XML编辑器,支持自动...

    XML深入浅出

    许多应用程序(如Apache服务器、Spring框架)使用XML文件进行配置,因为XML可以清晰地组织和表示层次结构。 九、XPath和XSLT XPath是查询XML文档中节点的语言,用于选取、导航和操作XML数据。XSLT(XSL ...

    XML文件资料

    XML文件的配置主要涉及命名空间、DTD(Document Type Definition)或XSD(XML Schema Definition)。命名空间允许在同一文档中使用相同标签但来自不同来源,防止冲突。DTD和XSD则用于定义XML文档的结构和数据类型,...

    xml文件解析资料汇总(个人收集)

    XML在Web服务(如SOAP)、配置文件(如Spring框架)、数据交换(如RSS、Atom)、文档存储(如DocBook)等方面有着广泛应用。理解并掌握XML的解析和操作是现代软件开发中的必备技能。 六、XML技巧与文摘 在实际使用...

    解析xml项目

    - 在"parsexml"项目中,可能包含了读取XML文件,通过DOM4J进行解析并处理数据的代码。 - 可能的应用场景有配置文件读取、数据交换、XML格式的API响应处理等。 7. **优化与注意事项**: - 大文件处理时,考虑使用...

    解析xml文件文档+实例+配置

    2. 解析:解析器读取XML文档,构建DOM(Document Object Model)树或SAX(Simple API for XML)事件流。 - DOM解析:将整个XML文档加载到内存中形成树形结构,便于查找和操作任意节点。 - SAX解析:逐行读取,事件...

Global site tag (gtag.js) - Google Analytics