Reputation: 31
I am making an API kind of thing for school for a custom XML writer. I have:
public Document CreateDocument(int loops, int attr, String data[], String dataattr[][][]) {
Document BetterDoc = DocumentHelper.createDocument();
Element root = BetterDoc.addElement("root");
for (int i = 0; i < loops; i++) {
Element(Object) data[i] = root.addElement(data[i])
for (int i2 = 0; i < attr; i++) {
.addAtribute(dataattr[i][i2][0], dataattr[i][i2][1])
};
}
return BetterDoc;
}
The line that I want help with is:
Element(Object) data[i] = root.addElement(data[i])
I want to create an element with the same name of the data[i].
I am using the dom4j XML .jar in this, by the way.
I have heard of something called a hashmap and if this is the correct method, would someone please explain how to use it.
Upvotes: 1
Views: 107
Reputation: 11949
You can't create dynamic variable unlike Groovy, PHP or Javascript, but you can create an array or reuse an existing variable:
With an existing variable:
public Document CreateDocument(int loops, int attr, String data[], String dataattr[][][]) {
Document BetterDoc = DocumentHelper.createDocument();
Element root = BetterDoc.addElement("root");
for (int i = 0; i < loops; i++) {
Element _data = root.addElement(data[i]);
for (int i2 = 0; i < attr; i++) {
_data.addAtribute(dataattr[i][i2][0], dataattr[i][i2][1])
};
}
return BetterDoc;
}
With an array:
public Document CreateDocument(int loops, int attr, String data[], String dataattr[][][]) {
Document BetterDoc = DocumentHelper.createDocument();
Element root = BetterDoc.addElement("root");
Element[] _data = new Element[loops];
for (int i = 0; i < loops; i++) {
_data[i] = root.addElement(data[i]);
for (int i2 = 0; i < attr; i++) {
_data[i].addAtribute(dataattr[i][i2][0], dataattr[i][i2][1])
};
}
return BetterDoc;
}
You can replace array with an ArrayList
if you prefer.
Upvotes: 0
Reputation: 121998
No. Simply you can't do that. You can't create/access a variable dynamically with it's name. With Reflection you can access but you can't create.
I guess, a map can do the task here just like
map.put(data[i],root.addElement(data[i]);
Above is just an example code to throw some light.
Upvotes: 3