gpt4 book ai didi

Java XML 转换器仅输出 XML header

转载 作者:行者123 更新时间:2023-12-01 14:07:39 29 4
gpt4 key购买 nike

我正在开发一个自娱自乐的项目,其中涉及将多个变量的内容输出到 XML 文件。然而,当我输入该程序时,转换器仅输出第一行(XML header )而没有其他内容。 saveData() 方法在 writeFile() 之前调用,并且在调用 writeFile() 之前我已将变量的值输出到控制台,因此我知道它们有一个值。

代码如下:

public class Output {   
private static double citySizeMiles;
private static double citySizeAcres;
private CityType type;
private static int gpLimit;
private static long totalWealth;
private static long cityPopulation;

public static void saveData() {
cityPopulation = CityGenerator.cityPop;
citySizeMiles = City.getCitySizeMiles(cityPopulation);
citySizeAcres = City.getCitySizeAcres(cityPopulation);
gpLimit = City.getGoldLimit();
totalWealth = CityGenerator.cityWealth;
}

public static void writefile() {
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = docFactory.newDocumentBuilder();

// Root Elements
Document doc = builder.newDocument();
Element root = doc.createElement("data");

// Data Element
Element data = doc.createElement("City");
root.appendChild(data);

Attr attr = doc.createAttribute("name");
attr.setValue("Test");
data.setAttributeNode(attr);

// City size (sq miles)
Element sizeMi = doc.createElement("sizeMiles");
sizeMi.appendChild(doc.createTextNode(String.valueOf(citySizeMiles)));
data.appendChild(sizeMi);

// City size (acres)
Element sizeAc = doc.createElement("sizeAcres");
sizeAc.appendChild(doc.createTextNode(String.valueOf(citySizeAcres)));
data.appendChild(sizeAc);

// Population
Element pop = doc.createElement("population");
pop.appendChild(doc.createTextNode(String.valueOf(cityPopulation)));
data.appendChild(pop);

// GP limit
Element gpLim = doc.createElement("gpLimit");
gpLim.appendChild(doc.createTextNode(String.valueOf(gpLimit)));
data.appendChild(gpLim);

// Total fluid wealth
Element wealth = doc.createElement("totalWealth");
wealth.appendChild(doc.createTextNode(String.valueOf(totalWealth)));
data.appendChild(wealth);

// Write to XML file
TransformerFactory tf = TransformerFactory.newInstance();
tf.setAttribute("indent-number", 4);

Transformer trans = tf.newTransformer();
trans.setOutputProperty(OutputKeys.INDENT, "yes");
trans.setOutputProperty(OutputKeys.METHOD, "xml");

DOMSource source = new DOMSource(doc);
//StreamResult result = new StreamResult(new File("D:\\test.xml"));

StreamResult result = new StreamResult(System.out);

trans.transform(source, result);

} catch(ParserConfigurationException pce) {
pce.printStackTrace();
} catch(TransformerException tfe) {
tfe.printStackTrace();
}
}
}

最佳答案

我不是 DOM 方面的专家(我像躲避瘟疫一样避免它,并鼓励其他人也这样做),但我认为你未能将根元素连接到文档节点。

关于Java XML 转换器仅输出 XML header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18770742/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com