Eclipse - XML模式定义

时间:2013-02-12 13:24:45

标签: xml eclipse

http://www.eclipse.org/modeling/mdt/?project=xsd#xsd。我们有文字:

“XML Schema Definition是一个参考库,它提供了一个API,用于检查,创建或修改W3C XML Schema的任何代码(独立或作为其他工件的一部分,如XForms或WSDL文档)。” p>

据此,我了解到我可以编写一个使用“XML Schema Definition”API创建XML文件的java类,并且这个创建的XML文件是我可以提供给EMF等工具的文件。 。假设我的理解是正确的(如果不是,请告诉我如何),我将在哪里找到这样一个java类的'hello world'类型示例?

1 个答案:

答案 0 :(得分:3)

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>