- 浏览: 468438 次
- 性别:
- 来自: 杭州
文章分类
- 全部博客 (146)
- Maven (3)
- Quartz (10)
- Hessian (3)
- JDK (42)
- eclipse (4)
- 设计思想 (6)
- XML (8)
- JavaMail (1)
- Spring (11)
- mina (1)
- HsqlDb (1)
- Cache (2)
- Tool (6)
- 心情 (5)
- JQuery (0)
- Hadoop (5)
- Hbase (3)
- 自动构建 (7)
- JNDI (0)
- 代码赏析 (5)
- Oracle (1)
- Excel (4)
- Effective Java (5)
- JAXB (4)
- fdafasdf (1)
- ccc (0)
- web (3)
- concurrent (1)
- CVS (1)
- eclipse plugin (2)
- Apache (10)
最新评论
-
chxiaowu:
nice!
Quartz实现固定执行次数 -
zxjlwt:
学习了。http://surenpi.com
自定义ClassLoader -
kadlly:
public static final Logger log ...
Hessian 权限认证 -
spring_springmvc:
java程序语言学习教程 地址http://www.zuida ...
Java-Final -
liushuiwuyan:
[img][/img]
设计模式-单例
主测试类如下:
说明
META-INF/myschema.schemas
myschema.schemas
说明
- 使用了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>
发表评论
-
Xml与Java Object 的转换[JAXB]
2013-12-09 15:25 8110package ycl.learn.xml.jaxb; ... -
dom,sax,dom4j,jdom,xerces
2013-04-10 16:41 3053dom,sax,dom4j,jdom的关系就不描述了.xerc ... -
xStream之xml
2013-04-10 15:36 17401. 把对象进行字符串输出,把字符串作为对象读入 pack ... -
Spring的schemaResolver
2012-12-18 11:01 1629Spring解析xml可以参考以上,可以指定自定义的schem ... -
Sax解析Xml
2012-12-12 14:01 997对于解析大型的xml,可能使用整个document或整个文件都 ... -
Xml转化为Java,Java转化为Xml[JAXB]
2012-12-12 13:51 1942JAXB:这是java处理xml的标 ... -
Spring,Struts的DTD验证
2010-10-12 11:04 7693一般比较正式的XML信息中都会包含对应的DTD声明,用来定义 ...
相关推荐
综上所述,DTD和Schema在Spring及Mybatis中起到了验证和规范XML配置文件的作用,保证了代码的稳定性和可维护性。了解并熟练掌握这些XML约束,对于理解和使用这两个框架至关重要。通过学习和实践,开发者可以更好地...
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=...
DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <bean id="helloBean" class="springdemo.HelloBean"> <value>Hello!chb!</value> </property> </...
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"> 7 8 9 <param-name>...
在实际应用中,XML常用于配置文件,如Web应用的Spring框架就大量使用XML配置。此外,它也用于Web服务之间的数据交换,如SOAP(Simple Object Access Protocol)消息就是基于XML的。 总结来说,XML是一种重要的数据...
- **SAX解析**:Simple API for XML,逐行读取XML,事件驱动。当遇到元素开始、结束、属性等时触发回调函数。适合处理大型XML文件,内存占用低,但操作相对复杂。 - **PULL解析**:类似于SAX,也采用事件驱动,但...
SAX(Simple API for XML)是一种事件驱动的解析方式,它不创建整个文档树,而是逐行读取XML,遇到开始标签、结束标签等事件时触发回调函数。SAX解析适用于大文件或内存有限的情况,因为它占用的资源较少。 四、...
XML常用于Web服务中的数据交换(如SOAP),配置文件(如Spring框架的配置),以及数据库存储(如MongoDB)。此外,它也被用作电子邮件标准(如RFC822的替代,即MIME)的一部分。 10. XML解析器: 各种编程语言都有...
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"> ...
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"> <!-- 事务...
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"> <!-- 定义bean.....
3. **命名空间问题**:Spring配置文件可能包含特定的命名空间,如`http://www.springframework.org/schema/beans`,这些命名空间需要正确的DTD或XSD来解析。 4. **Bean定义错误**:Bean的ID必须是唯一的,否则...
- SAX(简单API for XML)解析器:事件驱动型,逐行读取XML文件,适用于大文件处理。如javax.xml.parsers.SAXParserFactory和SAXParser。 - StAX(Streaming API for XML):流式解析,允许前后移动,平衡性能和...
4. XML Schema(XSD)和DTD(Document Type Definition):用于定义XML文档的结构和约束,确保数据的准确性和一致性。 5. 编写XML工具:许多IDE(集成开发环境)如Eclipse、IntelliJ IDEA提供了XML编辑器,支持自动...
许多应用程序(如Apache服务器、Spring框架)使用XML文件进行配置,因为XML可以清晰地组织和表示层次结构。 九、XPath和XSLT XPath是查询XML文档中节点的语言,用于选取、导航和操作XML数据。XSLT(XSL ...
XML文件的配置主要涉及命名空间、DTD(Document Type Definition)或XSD(XML Schema Definition)。命名空间允许在同一文档中使用相同标签但来自不同来源,防止冲突。DTD和XSD则用于定义XML文档的结构和数据类型,...
XML在Web服务(如SOAP)、配置文件(如Spring框架)、数据交换(如RSS、Atom)、文档存储(如DocBook)等方面有着广泛应用。理解并掌握XML的解析和操作是现代软件开发中的必备技能。 六、XML技巧与文摘 在实际使用...
- 在"parsexml"项目中,可能包含了读取XML文件,通过DOM4J进行解析并处理数据的代码。 - 可能的应用场景有配置文件读取、数据交换、XML格式的API响应处理等。 7. **优化与注意事项**: - 大文件处理时,考虑使用...
2. 解析:解析器读取XML文档,构建DOM(Document Object Model)树或SAX(Simple API for XML)事件流。 - DOM解析:将整个XML文档加载到内存中形成树形结构,便于查找和操作任意节点。 - SAX解析:逐行读取,事件...