简体   繁体   中英

How to add two or more elements of the same name at the same hierarchical level in an XML document using DOM in Java

I've been trying to create an XML document in Java using DOM where there are multiple car elements of the same name on the same hierarchical level, similar to the following:

<Root>
  <Car>
    <Make>Ford</Make>
    <Model>Fiesta</Model>
  </Car>
  <Car>
    <Make>VW</Make>
    <Model>Golf</Model>
  </Car>
</Root>

However, during construction of the XML, whenever I attempt to add another Car element, it seems to override the one that is already there, resulting in me only getting one Car element in my output.

I create the car element using the following code:

Element carElement = doc.createElement("Car");

And then attempt to append to the first Car element that I create using the following code:

root.appendChild(carElement);

I have also tried the following code to no avail:

Node existingCar = doc.getElementsByTagName("Car").item(0);
existingCar.getParentNode().insertBefore(carElement, existingCar);

The Java docs state that for both the appendChild() and insertBefore() methods, if the newChild node exists, then it will firstly be removed - hence why I think Im only seeing one output in my XML.

Therefore, can someone confirm whether or not this is possible with DOM? If so, can they please advise or point me in the direction of a solution? Thanks

I can confirm that this is possible with DOM!

You haven't shown us your actual code where you try to add more than one child element with the same name, so we cannot tell you exactly why it doesn't work. However, maybe this snippet will give you a hint of how to fix your code. To add five Car elements:

    DocumentBuilder b = ...;

    DOMImplementation impl = b.getDOMImplementation();
    Document d = impl.createDocument(null, "Root", (DocumentType) null);
    Element root = d.getDocumentElement();
    for (int i = 0; i < 5; ++i) {
        Element car = d.createElement("Car");
        // add sub-elements/attributes to car element
        ...
        root.appendChild(car);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM