JAXB中的Unmarshaller和模式 [英] Unmarshaller and schema in JAXB

查看:159
本文介绍了JAXB中的Unmarshaller和模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有可以以各种格式保存文件的应用程序(所有这些都是xml)。所以我应该在确定格式文件已保存的情况下解决问题。所以,我看到2个解决方案

I have application that can save file in various formats (all of them is xml). So I should solve problem with determination in what format file have been saved. So, I see 2 solutions


  • 不同的格式有不同的模式,所以我可以通过它们来确定。
    我按照这里的方式设置模式

  • different formats have different schemas, so I could determine it by them. I set schemas in way that I get from here

marshaller.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION,bla-bla.xsd);

所以我想我可以使用 unmarshaller.getProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION)

但抛出


javax.xml.bind.PropertyException:
jaxb.noNamespaceSchemaLocation

javax.xml.bind.PropertyException: jaxb.noNamespaceSchemaLocation

getSchema()返回null
所以,如何我可以获取架构位置吗?


  • 使用 setAdapter为类别指定不同的适配器(Class< A> ;类型,适配器)方法

  • Specifying different adapters for different beans using setAdapter(Class<A> type, A adapter) method

哪种方式更可取?如果是第一个,那么我该如何获得模式位置标签?

What way is preferable? If first, then how can I get schema location label?

upd 代码示例
假设我们有bean

upd code example suppose we have bean

@XmlRootElement
public class Foo{
    String bar;
    public String getBar() {return bar; }
    public void setBar(String bar) {this.bar = bar;}
}

和生成模式的代码,然后保存Foo的实例和加载。

and code that generates schema, saves Foo's instances and loads then.

public class Test {
    final static String schemaLoc = "fooschema.xsd";


    public static void write(File file, Foo foo, Schema schema) throws Throwable {
        XMLEventWriter xsw = null;
        try{
            JAXBContext context = JAXBContext.newInstance(Foo.class);
            XMLOutputFactory xof = XMLOutputFactory.newInstance();
            OutputStream out = new FileOutputStream(file);
            xsw = xof.createXMLEventWriter(out);
            Marshaller m = context.createMarshaller();
            m.setSchema(schema);    //schema setted
            System.out.println(">>>marchal : " + m.getSchema());    //check it
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            m.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, schemaLoc);
            m.marshal(foo, xsw);
        } finally{
             xsw.close();
        }
    }

    public static Foo load(File file) throws Throwable {
        JAXBContext context = JAXBContext.newInstance(Foo.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();


        System.out.println("unmarshaller schema:" + unmarshaller.getSchema());  //I need get it here
    //  System.out.println("schema_prop:" + unmarshaller.getProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION));

        InputStreamReader in = new InputStreamReader(new FileInputStream(file));
        XMLEventReader xer = XMLInputFactory.newInstance()
                .createXMLEventReader(in);
        return Foo.class.cast(unmarshaller.unmarshal(xer));
    }

    private static File createSchema(String schemaLocation) throws Throwable{
        final File target = new File(schemaLocation);
        if(!target.exists()){
            JAXBContext jaxbContext = JAXBContext.newInstance(Foo.class);
            SchemaOutputResolver sor = new SchemaOutputResolver() {
                public Result createOutput(String namespaceURI, String suggestedFileName)
                throws IOException {
                    StreamResult result = new StreamResult(target);
                    result.setSystemId(target.toURI().toURL().toString());
                    return result;
                }
            };
            jaxbContext.generateSchema(sor);
        }
        return target;
    }

    public static void main(String[] args) throws Throwable {
        createSchema(schemaLoc);
        File file = new File("temp.xml");
        Foo foo = new Foo();
        foo.setBar("test bar");
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = factory.newSchema(createSchema(schemaLoc));
        write(file, foo, schema);
        System.out.println("result " + load(file).getBar());
    }

}

生成
的架构

schema that generates

      <xs:element name="foo" type="foo"/>

      <xs:complexType name="foo">
        <xs:sequence>
          <xs:element name="bar" type="xs:string" minOccurs="0"/>
        </xs:sequence>
      </xs:complexType>
    </xs:schema>

我们的临时文件

<?xml version="1.0"?>
<foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="fooschema.xsd">
<bar>test bar</bar></foo>

如我们所见,有


xsi:noNamespaceSchemaLocation =fooschema.xsd

xsi:noNamespaceSchemaLocation="fooschema.xsd"

如何使用JAXB获取此文本?

How I can get this text using JAXB?

推荐答案

我会利用StAX解析器来获取这些信息(参见下面的示例)。在输入上创建XMLStreamReader。使用 nextTag()方法将XMLStreamReader推进到根元素。然后获取根元素的noNamespaceSchemaLocation属性。然后将XMLStreamReader传递给Unmarshaller上的 unmarshal(XMLStreamReader)方法。

I would leverage a StAX parser to get this information (see example below). Create an XMLStreamReader on the input. Advance the XMLStreamReader to the root element using the nextTag() method. Then grab the noNamespaceSchemaLocation attribute of the root element. Then pass the XMLStreamReader to the unmarshal(XMLStreamReader) method on Unmarshaller.

import java.io.FileInputStream;
import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext context = JAXBContext.newInstance(Categories.class);

        XMLInputFactory xif = XMLInputFactory.newInstance();
        FileInputStream fis = new FileInputStream("input.xml");
        XMLStreamReader xsr = xif.createXMLStreamReader(fis);
        xsr.nextTag();
        String noNamespaceSchemaLocation = xsr.getAttributeValue(XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI, "noNamespaceSchemaLocation");
        System.out.println(noNamespaceSchemaLocation);

        Unmarshaller um = context.createUnmarshaller();
        Categories response = (Categories) um.unmarshal(xsr);
    }
}

这篇关于JAXB中的Unmarshaller和模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆