【发布时间】:2015-04-14 07:10:46
【问题描述】:
我正在通过 Java 创建几个 XML 文件,到目前为止一切正常,但现在我在尝试创建具有命名空间前缀节点的文件时遇到了问题,即使用重构的 <tns:node> ... </tns:node> 之类的东西我的代码版本已经适用于没有命名空间的普通 xml 文件。
抛出的错误是:
org.w3c.dom.DOMException: INVALID_CHARACTER_ERR: Ungültiges XML-Zeichen angegeben.
对不起那里的德国人,上面写着“指定的 XML 符号无效”。
发生错误的代码行:
Element mainRootElement = doc.createElement("tns:cmds xmlns:tns=\"http://abc.de/x/y/z\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://abc.de/x/y/z xyzschema.xsd\"");
为了消除错误导致转义相当长的字符串或其他内容的可能性,我也尝试使用Element mainRootElement = doc.createElement("tns:cmds");,但是,这会导致相同的错误。
这就是为什么我认为它与命名空间声明有关,即 : 曾经这样做,因为这是我能想到的字符串中唯一的“无效”字符。
谁能确认这是问题的根源?如果是这样,是否有一个简单的解决方案? Java DOM 可以使用命名空间标签吗?
编辑:整个方法供参考
private void generateScriptXML()
{
DocumentBuilderFactory icFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder icBuilder;
try
{
icBuilder = icFactory.newDocumentBuilder();
Document doc = icBuilder.newDocument();
Element mainRootElement = doc.createElement("tns:cmds xmlns:tns=\"http://abc.de/x/y/z\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://abc.de/x/y/z xyzschema.xsd\"");
doc.appendChild(mainRootElement);
mainRootElement.appendChild(getAttributes(doc,"xxx", "yyy", "zzz"));
mainRootElement.appendChild(getAttributes(doc,"aaa", "bbb", "ccc"));
mainRootElement.appendChild(getAttributes(doc,"ddd", "eee", "fff"));
...
...
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);
StreamResult streamResult = new StreamResult(new File(vfsPath));
transformer.transform(source, streamResult);
}
catch (Exception e)
{
e.printStackTrace();
}
}
【问题讨论】:
标签: java xml dom namespaces