Java XML 创建结束 xml 语句,但没有打开语句



我有一个创建xml文档的程序。

文件名在这里并不重要,因为文件确实成功创建 条目的数组列表包含一个唯一标识符和一个 元素 + 值。 元素如下:世界、名称、位置、类型和数据 所有这些值都是字符串,唯一为空/空的值是数据 我的问题是XML文件根据需要添加所有字段,但例外 的数据字段。 它给我留下了一个未打开的节点.实际结果:

<NPC>
<NPC:0>
<name>
the_name
</name>
<data/>  <---- this line should have the string "null"
<loc>
2529.1294962948955:
69.0:
951.2612160649056
</loc>
<type>
Quest
</type>
<world>
world
</world>
</NPC:0>
</NPC>

我创建 xml 文件的方法。

public void updateXML(String fileName, ArrayList<XMLEntry> entries)
{
File file = getFileByName(fileName);
try {
DocumentBuilderFactory bFac = DocumentBuilderFactory.newInstance();
DocumentBuilder b = bFac.newDocumentBuilder();
Document doc = b.parse(file);
for(int i = 0; i < entries.size(); i++)
{
XMLEntry entry = entries.get(i);
Node entry_node = doc.getElementsByTagName(entry.getName()).item(0);
if(entry_node == null)
{
Element node = doc.createElement(entry.getName());
doc.getFirstChild().appendChild(node);
entry_node = doc.getElementsByTagName(entry.getName()).item(0);
}
for (Map.Entry<String, String> attributes : entry.getAttributes().entrySet())
{
NamedNodeMap xml_attributes = entry_node.getAttributes();
Node attribute = xml_attributes.getNamedItem(attributes.getKey());
if(attribute == null)
{
if(attributes.getValue() != "" || attributes.getValue() != null)
{
Element new_xml_attribute = doc.createElement(attributes.getKey());
new_xml_attribute.appendChild(doc.createTextNode(attributes.getValue()));
entry_node.appendChild(new_xml_attribute);
} else {
Element new_xml_attribute = doc.createElement(attributes.getKey());
new_xml_attribute.appendChild(doc.createTextNode("null"));
entry_node.appendChild(new_xml_attribute);
}
} else {
attribute.setTextContent(attributes.getValue());
}
TransformerFactory tFac = TransformerFactory.newInstance();
Transformer ts = tFac.newTransformer();
DOMSource src = new DOMSource(doc);
StreamResult result = new StreamResult(file);
ts.transform(src, result);
}
}
} catch (ParserConfigurationException e) {
} catch (TransformerException e1) {
} catch (IOException e2) {
} catch (SAXException e3) {
}
}
<data/>  <---- this line should have the string "null"

这不是 XML 紧密元素标记(这将是</data>)。它是一个 XML 空元素标记,它将打开和关闭组合到单个标记中。它在语义上与<data></data>相同

尽管您期望,但空<data/>元素似乎不是由具有文本"null"的路径创建的。将打印输出拖放到该代码中,或在调试器中运行它以确认这一点。然后使用调试器,或根据需要放入其他打印输出,以找出原因。

最新更新