如何在运行时将 JAXB 注释 class 转换为 Schema 实例?
How to convert JAXB annotated class to Schema instance at runtime?
我知道在编译时创建模式 (JAXB),但我如何在运行时获取此信息。
型号class:
package pl.kkrzeminski;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Model {
@XmlElement(required = true)
private String text;
}
如何基于 JAXB 元数据在运行时创建架构实例 Model.java?
package pl.kkrzeminski;
import org.xml.sax.SAXException;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.SchemaFactory;
import java.io.ByteArrayInputStream;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws SAXException, IOException {
SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
// TODO how can i create at runtime instance of Schema based on Model.java?
javax.xml.validation.Schema schema = sf.newSchema(new Source[]{});
schema.newValidator().validate(new StreamSource(new ByteArrayInputStream("<model><text>test</text></model>".getBytes())));
}
}
在此处找到解决方案 (nazgul-core-xmlbinding-spi-jaxb):
JAXB Validation Without Schema
替换:
toReturn.setSystemId("");
与:
toReturn.setSystemId(suggestedFileName);
我知道在编译时创建模式 (JAXB),但我如何在运行时获取此信息。
型号class:
package pl.kkrzeminski;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Model {
@XmlElement(required = true)
private String text;
}
如何基于 JAXB 元数据在运行时创建架构实例 Model.java?
package pl.kkrzeminski;
import org.xml.sax.SAXException;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.SchemaFactory;
import java.io.ByteArrayInputStream;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws SAXException, IOException {
SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
// TODO how can i create at runtime instance of Schema based on Model.java?
javax.xml.validation.Schema schema = sf.newSchema(new Source[]{});
schema.newValidator().validate(new StreamSource(new ByteArrayInputStream("<model><text>test</text></model>".getBytes())));
}
}
在此处找到解决方案 (nazgul-core-xmlbinding-spi-jaxb): JAXB Validation Without Schema
替换:
toReturn.setSystemId("");
与:
toReturn.setSystemId(suggestedFileName);