我正在尝试使用Java编写一个xml文件,我想将一个变量字符串发送到方法document.createElement(var),但它给了我这个错误:
"Exception in thread "main" org.w3c.dom.DOMException: INVALID_CHARACTER_ERR: An invalid or illegal XML character is specified.
at com.sun.org.apache.xerces.internal.dom.CoreDocumentImpl.createElement(Unknown Source)
at eg.edu.alexu.csd.oop.draw.WriteXML.<init>(WriteXML.java:47)
at eg.edu.alexu.csd.oop.draw.Test.main(Test.java:25)"
此错误,因为var是变量
public class WriteXML {
public WriteXML() throws FileNotFoundException, ParserConfigurationException, IOException{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document xmlDoc = docBuilder.newDocument();
for(int i=0 ; i<shapes.length ; i++){
//class
s = shapes[i].getClass().getName().toString();
Element rootElement = xmlDoc.createElement(s);
}
答案 0 :(得分:1)
数字不能用作标记名称。这是一个简化的测试:
// Generates the error
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document xmlDoc = docBuilder.newDocument();
xmlDoc.createElement("0");
您可以使用属性或文本内容来设置数字。
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document xmlDoc = docBuilder.newDocument();
xmlDoc.createElement("Red").setTextContent("0");
我不确定,但我认为相关的一行是:
[定义:名称是一个Nmtoken,其中包含一组有限的初始字符。]名称不允许的初始字符包括数字,变音符号,句号和连字符。