Reputation: 169
I am trying to write an xml file using Java and I want to send a variable string to the method document.createElement(var) ,but it gives me that error:
"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)"
this error because var is a variable
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);
}
Upvotes: 1
Views: 2499
Reputation: 997
A number cannot be used as a tag name. Here is a simplified test:
// Generates the error
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document xmlDoc = docBuilder.newDocument();
xmlDoc.createElement("0");
You can use an attribute, or text content, to set the number.
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document xmlDoc = docBuilder.newDocument();
xmlDoc.createElement("Red").setTextContent("0");
I am not sure, but I think the related line is:
[Definition: A Name is an Nmtoken with a restricted set of initial characters.] Disallowed initial characters for Names include digits, diacritics, the full stop and the hyphen.
Upvotes: 1