通常我们需要根据xsd文件生成java代码,具体操作和生成xml一并介绍
1.根据xsd生成相应的java类:
cmd进入jdk的bin目录:
执行如下命令即可生成java类,xjc –d java类的存放路径 –p 类的包名 xsd文件名
例如:C:\Program Files (x86)\Java\jdk1.6.0_37\bin>xjc -d c:\zeb\1212 C:\zeb\1212\xx\PP
M\TRM\TRM_WorkOrderList.xsd
2. 根据xsd可以生成测试xml数据,用eclipse等工具可以生成测试数据,右键xsd文件Generate→xml files
3. 解析xml文件,代码如下:
import java.io.File;
import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.SchemaFactory;
import org.nssd.JElem;
public class Test {
public static void main(String[] args) {
JAXBContext context;
try {
context = JAXBContext.newInstance(JElem.class);
Unmarshaller shaller = context.createUnmarshaller();
shaller.setSchema(SchemaFactory.newInstance(
XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(
new File("src/myxsd.xsd")));
JAXBElement root = shaller.unmarshal(new StreamSource(new File("src/data.xml")),JElem.class);
JElem jElem = root.getValue(); //JElem是xml文件的根节点
} catch (Exception e) {
e.printStackTrace();
}
}
}