1

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.

john
  • 1,561
  • 3
  • 20
  • 44
Piemansam5
  • 31
  • 7
  • Please, follow Java coding conventions. Take a look at http://stackoverflow.com/questions/23738010/java-print-string-c-equivalent – Dmitry Ginzburg Sep 22 '14 at 12:11
  • take a look at http://stackoverflow.com/questions/19153930/how-to-create-java-beans-dynamically – Leo Sep 22 '14 at 12:18

2 Answers2

3

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.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

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.

NoDataFound
  • 11,381
  • 33
  • 59