1
这是我将XML文件创建为Java对象的方式。 我使用了“xjc”和一个有效的XML模式,并且我找回了一些“生成的”* .java文件。 我在日食中将它们导入到不同的包中。 我正在以2种方式读取XML文件。XML解析java确认
1)加载XML文件:
System.out.println("Using FILE approach:");
File f = new File ("C:\\test_XML_files\\complex.apx");
JAXBElement felement = (JAXBElement) u.unmarshal(f);
MyObject fmainMyObject = (MyObject) felement.getValue();
2)使用DOM Builder也随之:
System.out.println("Using DOM BUILDER Approach:");
JAXBElement element = (JAXBElement) u.unmarshal(test());;
MyObject mainMyObject = (MyObject) element.getValue();
现在
在方法 “测试()” 下面的代码包含:
public static Node test(){
Document document = parseXmlDom();
return document.getFirstChild();
}
private static Document parseXmlDom() {
Document document = null;
try {
// getting the default implementation of DOM builder
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
// parsing the XML file
document = builder.parse(new File("C:\\test_XML_files\\MyXML_FILE.apx"));
} catch (Exception e) {
// catching all exceptions
System.out.println();
System.out.println(e.toString());
}
return document;
}
这是执行XML到Java对象的标准方式吗? 我测试了如果我可以访问该对象,一切正常。 (到目前为止) 你建议采用不同的方法吗?或者这是否足够?
有很多方法可以访问XML。至于JAXB,请查看http://download.oracle.com/javase/6/docs/api/javax/xml/bind/Unmarshaller.html - 它们的示例包括您的两种方法和更多。 – 2011-02-19 01:22:51
你在寻找DOM对象还是Java XML绑定? – gigadot 2011-02-19 01:43:37