Search code examples
javaxmlparsexml

Random String, in cloned node.Java


This is my code which clones XML nodes.

int numberOfNewOffers = Integer.parseInt(oProps.getProperty("prop2","3"));
Node offers = doc.getDocumentElement().getElementsByTagName("OF_DATA").item(0);
Node offer = null;
for (int i = 0; i < offers.getChildNodes().getLength(); ++i) {
  if (offers.getChildNodes().item(i).getNodeName() == "OFX") {
    offer = offers.getChildNodes().item(i);
  }
}
if (offer != null) {
  for (int i = 0; i < numberOfNewOffers; ++i) {
    Node newOffer = offer.cloneNode(true);
    offers.appendChild(newOffer);
  }
}

These are my cloned nodes:

<OF_DATA>
  <OFX>
    <ID>AVI</ID>
    <ON>6</ON>
    <END>11001</END>
    <NAME>Ed</NAME>
  </OFX>
  <OFX>
    <ID>AVI</ID>
    <ON>6</ON>
    <END>11001</END>
    <NAME>Ed</NAME>
  </OFX>
  <OFX>
    <ID>AVI</ID>
    <ON>6</ON>
    <END>11001</END>
    <NAME>Ed</NAME>
  </OFX>
</OF_DATA>

How can I make it so that the <ID> elements in each clone are always different? I've been told to use random.


Solution

  • If you have only one thread, you may use as this: int nextId; when cloning, use yourNodeId=nextId++; And you may save and restore the nextId value to and from disk if you want the id be unique even after the program restart.

    If you have multi threads: try using the advice above but with a lock. Or give every thread a region(for example, thread1 is given 0-100000, thread2 is given 100000-200000), then do as above.