javaxmljdomjdom-2

JDOM 2 Get position and index of a specific XML element


I have an XML document and I want to add an element in a specific position (index) using the name and attribute of existing element, So I have to find the index of this specific element.

Example:

<root org="667">
<myobject name="Propert1">KS7799</p>
<myobject name="Propert2">88YSJJ</p>
<myobject name="Propert3">KKQ87</p>
<myobject name="Propert4">122ZKK</p>
<myobject name="Propert5">LQLX9</p>
<myobject name="Propert6">LLQS8</p> // I want to get index of this element
<myobject name="Propert7">LLLX9</p>
<myobject name="Propert8">LLSSKNX9</p>
<myobject name="Propert9">MQLKSQ9</p>
<myobject name="Propert10">MLKLKQSQ9</p>
</root>

My code:

 for (Element ObjectElement : Dataelement.getChildren("myobject")) {


                Attribute nameattr_class = ObjectElement.getAttribute("name");


                if (nameattr_class.getValue().equals("Propert6")) {

                   // I want to index of this element
                }


      }

Solution

  • If you know the element you want to insert after, there are a few things you can do....

    You can get an Iterator on the collection, and just add the element.... like:

    Element toinsert = new Element("toinsert");
    
    Iterator<Element> it = Dataelement.getChildren("myobject");
    while (it.hasNext() && !"Propert6".equals(it.next().getAttribute("name"))) {
        // advance the iterator.
    }
    it.add(toinsert);
    

    Alternatively, you can find the Element with the right property using, for example, an XPath.....

    XPathFactory xpf = XPathFactory.instance();
    XPath<Element> xp = xpf.compile("//myobject[@name='propert6']", Filters.element());
    Element propert6 = xp.evaluateFirst(Dataelement);
    
    Element toinsert = new Element("toinsert");
    Element parent = toinsert.getParent();
    parent.addContent(parent.indexOf(propert6), toinsert);