我一直致力于将数据转换为基于XML的Collada .DAE格式的工具。不幸的是,有一件事阻止了我:我导出的XML没有任何元素!
这是代码。我已经让它易于阅读,所以你不必经历阅读它的麻烦。
public class DAEExport {
private static boolean alreadyConstructed = false;
private static Document doc = null;
private static Element root = null;
private static Element lib_images_base_element = null;
private static Element lib_geometry_base_element = null;
private static Element lib_control_base_element = null;
private static Element lib_visual_scene_base_element = null;
public static void AppendData() {
//Normally this method would have the data to append as its args, but I'm not worried about that right now.
//Furthermore, ASSUME THIS RUNS ONLY ONCE (It runs once in the test code I'm using to run this method)! I know that it won't work if called multiple times, as the below variables for the document builder and such wouldn't exist the second time around
try {
if (!alreadyConstructed) {
alreadyConstructed = true;
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document document = docBuilder.newDocument();
Element rootElement = document.createElement("SomeGenericElement");
rootElement.appendChild(document.createTextNode("Generic test contents");
document.appendChild(rootElement);
doc = document;
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void Build(File _out) {
try {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);
alreadyConstructed = false;
doc = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
好的,这就是我的问题:尽管通过调用AppendData()
将这些元素添加到文档中,然后调用Build()
来打印数据,我只获得以下数据:
<?xml version="1.0" encoding="UTF-8"?>
- 没有元素。只是基本的标题。就是这样。
我不知道是不是因为一些愚蠢的错误,我在过去的一段时间内都没有注意到,或者别的什么。关于为什么我的元素消失的任何答案?
答案 0 :(得分:0)
目前,您的doc
对象未从AppendData()
方法传递到Build()
方法。所有Build()
使用都是来自声明的空文档:doc = null
。因此,您的结果是空的节点(TransformFactory添加XML标头)。
考虑将doc
对象从AppendData()
返回到其他方法的类级别(请注意将void更改为返回的对象类型)。然后,您重新定义doc
并将其传递到Build()
:
public static Document AppendData() {
...
doc = document
return(doc)
}
或者,在Build()
内拨打AppendData
,将doc
作为参数传递:
public static void AppendData() {
...
doc = document
Build(doc, outfile)
}
public static void Build(Document doc, File _out) {
...
}