我一直在研究一種將數據轉換爲基於XML的Collada .DAE格式的工具。不幸的是,有一件事一直在阻止我:我的導出XML沒有任何我的元素!我的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"?>
- 無元素。只是基本的標題。就是這個。
我不知道是否因爲一些愚蠢的錯誤,我忘記了過去的時間或其他東西。任何答案爲什麼我的元素消失?
我仍然有種困惑,爲什麼DOC仍然'null' 。我知道它可以是null,但如果我調用AppendData()它不會再爲空,因此'doc = document'行? –
編輯:我將它從'Document document = docBuilder.newDocument();'改爲'doc = docBuilder.newDocument()',並且將'private static Document doc = null;'改爲'private static Document doc;'和它現在似乎工作。仍然有點困惑,爲什麼這個工作,而另一種方式沒有。 –
很好,它解決了。再次,您之前的設置確實操作了'doc',但僅限於這種情況下,'AppendData()'。一旦方法完成而沒有返回操作的'doc'對象不再可用。 'Build()'只能看到初始化的'doc'(沒有被操縱的)空值。 – Parfait