开发者

Java Xml to Object?

开发者 https://www.devze.com 2023-04-12 14:53 出处:网络
What are the steps getting an (model) object from an XML file? Given an XSD and JAXB dependency at Spring 3, built with Maven u开发者_运维技巧sing Java 1.6.

What are the steps getting an (model) object from an XML file?

Given an XSD and JAXB dependency at Spring 3, built with Maven u开发者_运维技巧sing Java 1.6.

Note: I am new to Spring and that technologies.

What I tried

I put that dependency (can I use a newer version):

    <dependency>
        <groupId>org.springframework.ws</groupId>
        <artifactId>spring-oxm-tiger</artifactId>
        <version>1.5.4</version>
    </dependency>

and that

        <plugin>
            <groupId>org.jvnet.jaxb2.maven2</groupId>
            <artifactId>maven-jaxb2-plugin</artifactId>
            <executions>
                <execution>
                    <id>generate-oxm</id>
                    <goals>
                        <goal>generate</goal>
                    </goals>
                    <configuration>
                        <schemaDirectory>src/main/resources/META-INF/xsd</schemaDirectory>
                        <generatePackage>com.aaa.xjc</generatePackage>
                    </configuration>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <inherited>true</inherited>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.6</source>
                <target>1.6</target>
            </configuration>
        </plugin>

to my POM file.

I made a class like that:

@Configuration
public class XmlAdapter {
    @Autowired
    private ResourcePatternResolver resourceResolver;

    @Bean
    public Jaxb2Marshaller oxmMarshaller() throws IOException {
        Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
        marshaller.setContextPath("com.aaa.xjc");
        marshaller.setSchemas(resourceResolver.getResources("classpath:/META-INF/xsd/*.xsd"));
        return marshaller;
    }

}

Problem

Actually I didn't understand that context path and how to call that oxmMarshaller method.

How can I use my existing XSD to validate them? I tried that according to my previous question: Xml to Object java Spring 3


You will first need to run xjc on the XSD to generate the JaxB classes. You will then need to create these JaxB objects, ideally using the generated ObjectFactory. At that point you can send that object to the JaxB2Marshaller. If you want to return as a response in a web application, you can use the MarshallingView.

As far as the maven deps, all the JaxB stuff will be included with Java 6. You will need to properly manage the spring deps. At the very least, you will need Spring OXM.


  1. Run xjc on the schema to generate the java classes. XJC
  2. Use the JaxB Unmarshaller to parse the file. Unmarshalling
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号