繁体   English   中英

如何从EMF中创建符合XSD的XML实例?

[英]How to create a XSD-conformant XML instance out of an EMF?

我的应用程序的目标是创建符合XSD文件的XML配置文件。 我要实现这一目标的计划如下:1.我从xsd文件中创建一个ecore模型2.从该ecore模型中,我生成了Java类(通过genmodel)。3.在当前配置实例中需要填充的类值4.现在,我以某种方式创建一个XML文件。

在第2步中的conf.xsd中,创建了三个不同的文件夹,其中填充了java类:Conf,Conf.impl和Conf.util。 通过ConfFactoryImpl.init(),我创建了ConfFactory。 现在,根据以下文章( 如何将Ecore的XMI模型实例转换为给定XSD的XML? ),如果我理解正确的话,我可以使用XMLResource以某种方式创建XML文件。 但是我仍然在努力与此。 我的JAVA相当生锈(在最近几年中,Havent一直使用它),因此,我会为任何提示提供帮助。

这可能会有所帮助。 这是从现有的.XSD用Java创建XML文件的示例

XSD:

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
 xmlns:jxb="http://java.sun.com/xml/ns/jaxb"
 jxb:version="2.0">

<xsd:element name="Greetings" type="GreetingListType"/>
 <xsd:complexType name="GreetingListType">
  <xsd:sequence>
   <xsd:element name="Greeting" type="GreetingType"
         maxOccurs="unbounded"/>
  </xsd:sequence>
 </xsd:complexType>
 <xsd:complexType name="GreetingType">
  <xsd:sequence>
   <xsd:element name="Text" type="xsd:string"/>
  </xsd:sequence>
  <xsd:attribute name="language" type="xsd:language"/>
</xsd:complexType>

</xsd:schema>

Java类:

import java.util.*;
import javax.xml.bind.*;
import hello.*;

public class Hello {

private ObjectFactory of;
private GreetingListType grList;

public Hello(){
 of = new ObjectFactory();
 grList = of.createGreetingListType();
}

 public void make( String t, String l ){
   GreetingType g = of.createGreetingType();
   g.setText( t );
   g.setLanguage( l );
   grList.getGreeting().add( g );
 }

public void marshal() {
  try {
       JAXBElement<GreetingListType> gl =
        of.createGreetings( grList );
        JAXBContext jc = JAXBContext.newInstance( "hello" );
        Marshaller m = jc.createMarshaller();
         m.marshal( gl, System.out );
       } catch( JAXBException jbe ){
    // ...
  }
}

}

例:

Hello h = new Hello();
h.make( "Bonjour, madame", "fr" ); 
h.make( "Hey, you", "en" ); 
h.marshal();

输出:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Greetings>
<Greeting language="fr">
<Text>Bonjour, madame</Text>
</Greeting>
<Greeting language="en">
<Text>Hey, you</Text>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM