I experienced that Jaxb2Marshaller failed to validate my invalid XML against the XSD while doing the unmarshalling. I'm using Spring 4.0.0.RELEASE and Java 7.
Here is an example:
The XSD file: fruit.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified">
<xs:attribute name="quantity" type="xs:string" />
<xs:element name="fruit">
<xs:complexType>
<xs:sequence>
<xs:choice>
<xs:element ref="banana" />
<xs:element ref="apple" />
</xs:choice>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="banana">
<xs:complexType>
<xs:attribute ref="quantity" use="required" />
</xs:complexType>
</xs:element>
<xs:element name="apple">
<xs:complexType>
<xs:attribute ref="quantity" use="required" />
</xs:complexType>
</xs:element>
</xs:schema>
I generated the JAXB POJOs from this XSD with Spring Tool Suite to com.testraptor.xml.jaxb package.
My invalid XML file: invalid.xml
<?xml version="1.0" encoding="UTF-8"?>
<fruit>
<banana quantity="5" />
<apple quantity="3" />
</fruit>
As you can see I broke the schema because there is a choice in the fruit tag and I used banana and apple at the same time.
My Spring configuration file: app-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:oxm="http://www.springframework.org/schema/oxm"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/oxm
http://www.springframework.org/schema/oxm/spring-oxm-4.0.xsd">
<oxm:jaxb2-marshaller id="marshaller" context-path="com.fruit.xml.jaxb" />
</beans>
The main class to test: Main.java
package com.fruit.test;
import java.io.IOException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.Resource;
import org.xml.sax.SAXException;
import com.fruit.xml.jaxb.Fruit;
public class Main {
public static void main(String[] args) {
ApplicationContext appContext = new ClassPathXmlApplicationContext(
"app-context.xml");
//--------------------------------SCHEMA VALIDATION IS OMITTED
Jaxb2Marshaller jaxb2Unmarshaller = (Jaxb2Marshaller) appContext
.getBean("marshaller");
Resource schemaResource = appContext
.getResource("classpath:fruit.xsd");
jaxb2Unmarshaller.setSchema(schemaResource);
Resource xml = appContext.getResource("classpath:invalid.xml");
try {
Fruit fruit = (Fruit) jaxb2Unmarshaller.unmarshal(new StreamSource(xml.getInputStream()));
System.out.println("SCHEMA VALIDATION IS OMITTED:");
System.out.println("Apple quantity is " + fruit.getApple().getQuantity());
System.out.println("Banana quantity is " + fruit.getBanana().getQuantity());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//--------------------------------SCHEMA VALIDATION IS PASSED
SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema;
try {
schema = sf.newSchema(schemaResource.getURL());
JAXBContext context = JAXBContext.newInstance(Fruit.class);
Unmarshaller unmarshaller = (Unmarshaller) context.createUnmarshaller();
unmarshaller.setSchema(schema);
Fruit fruit2 = (Fruit) unmarshaller.unmarshal(xml.getInputStream());
System.out.println("SCHEMA VALIDATION IS PASSED:");
System.out.println("Apple quantity is " + fruit2.getApple().getQuantity());
System.out.println("Banana quantity is " + fruit2.getBanana().getQuantity());
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
When I run the code I get the following result:
INFO: Loading XML bean definitions from class path resource [app-context.xml]
dec. 26, 2013 9:33:22 DE org.springframework.oxm.jaxb.Jaxb2Marshaller createJaxbContextFromContextPath
INFO: Creating JAXBContext with context path [com.fruit.xml.jaxb]
SCHEMA VALIDATION IS OMITTED:
Apple quantity is 3
Banana quantity is 5
javax.xml.bind.UnmarshalException
- with linked exception:
[org.xml.sax.SAXParseException; lineNumber: 4; columnNumber: 24; cvc-complex-type.2.4.d: Invalid content was found starting with element 'apple'. No child element is expected at this point.]
at ...
As you can see the Jaxb2Marshaller forgot to validate my invalid XML file while the Unmarshaller could validate it.
Can anyone give me a clue what could be wrong with my code?
最佳答案
我在运行时配置 Jaxb2Marshaller 时遇到了同样的问题。通过 Spring XML 设置模式的建议解决方案让我开始思考:我的代码设置属性和 Spring 之间有什么区别?
答案很简单:Jaxb2Marshaller 实现 org.springframework.beans.factory.InitializingBean 定义了生命周期方法 afterPropertiesSet() 和这个方法在设置属性后由 Springs BeanFactory 调用。
因此解决方案是在使用 setSchema() 设置架构属性后调用 afterPropertiesSet()。因为在该方法中,模式属性(它是一个 org.springframework.core.io.Resource 数组)实际上用于设置类型为 javax.xml.validation.Schema 的内部模式字段 稍后用于模式验证。
示例:
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
Resource schema = new ClassPathResource("fruit.xsd");
marshaller.setSchema(schema);
marshaller.setContextPath("com.fruit.xml.jaxb");
// manually call Spring lifecycle method which actually loads the schema resource
marshaller.afterPropertiesSet();
// use marshaller...
关于java - Jaxb2Marshaller 模式验证似乎不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20782120/
我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende
我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/
我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www
给定一个复杂的对象层次结构,幸运的是它不包含循环引用,我如何实现支持各种格式的序列化?我不是来讨论实际实现的。相反,我正在寻找可能会派上用场的设计模式提示。更准确地说:我正在使用Ruby,我想解析XML和JSON数据以构建复杂的对象层次结构。此外,应该可以将该层次结构序列化为JSON、XML和可能的HTML。我可以为此使用Builder模式吗?在任何提到的情况下,我都有某种结构化数据-无论是在内存中还是文本中-我想用它来构建其他东西。我认为将序列化逻辑与实际业务逻辑分开会很好,这样我以后就可以轻松支持多种XML格式。 最佳答案 我最
我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我
什么是ruby的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht
这篇文章是继上一篇文章“Observability:从零开始创建Java微服务并监控它(一)”的续篇。在上一篇文章中,我们讲述了如何创建一个Javaweb应用,并使用Filebeat来收集应用所生成的日志。在今天的文章中,我来详述如何收集应用的指标,使用APM来监控应用并监督web服务的在线情况。源码可以在地址 https://github.com/liu-xiao-guo/java_observability 进行下载。摄入指标指标被视为可以随时更改的时间点值。当前请求的数量可以改变任何毫秒。你可能有1000个请求的峰值,然后一切都回到一个请求。这也意味着这些指标可能不准确,你还想提取最小/
HashMap中为什么引入红黑树,而不是AVL树呢1.概述开始学习这个知识点之前我们需要知道,在JDK1.8以及之前,针对HashMap有什么不同。JDK1.7的时候,HashMap的底层实现是数组+链表JDK1.8的时候,HashMap的底层实现是数组+链表+红黑树我们要思考一个问题,为什么要从链表转为红黑树呢。首先先让我们了解下链表有什么不好???2.链表上述的截图其实就是链表的结构,我们来看下链表的增删改查的时间复杂度增:因为链表不是线性结构,所以每次添加的时候,只需要移动一个节点,所以可以理解为复杂度是N(1)删:算法时间复杂度跟增保持一致查:既然是非线性结构,所以查询某一个节点的时候