0

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.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
simply_red
  • 29
  • 9

1 Answers1

0

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.

ch271828n
  • 15,854
  • 5
  • 53
  • 88