简体   繁体   English

如何在Java中使用DOM在XML文档中的相同层次结构级别上添加两个或多个相同名称的元素

[英]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: 我一直在尝试使用DOM在Java中创建XML文档,其中在相同的层次结构级别上有多个具有相同名称的汽车元素,类似于以下内容:

<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. 但是,在XML的构造过程中,每当我尝试添加另一个Car元素时,它似乎都会覆盖已经存在的Car元素,导致我在输出中仅获得一个Car元素。

I create the car element using the following code: 我使用以下代码创建car元素:

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

And then attempt to append to the first Car element that I create using the following code: 然后尝试附加到我使用以下代码创建的第一个Car元素:

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. Java文档指出,对于appendChild()和insertBefore()方法,如果newChild节点都存在,则首先将其删除-因此,为什么我认为Im仅在XML中看到一个输出。

Therefore, can someone confirm whether or not this is possible with DOM? 因此,有人可以确认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! 我可以确认使用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: 要添加五个Car元素:

    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);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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