Sample code for 30+ languages & platforms
Java

Insert after Node with Tag

See more XML Examples

Demonstrates how to insert a new node as a sibling directly after a specified node having a given tag.

Note: This example requires Chilkat v9.5.0.76 or greater. The TagIndex method was introduced in v9.5.0.76

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.Xml;

public class ChilkatExample {

    public static void main(String[] args) {
        // First, let's create the following XML:

        //   <FatturaElettronicaHeader>
        //     <DatiTrasmissione>
        //       <IdTrasmittente>
        //         <IdPaese>IT</IdPaese>
        //         <IdCodice>12345678</IdCodice>
        //       </IdTrasmittente>
        //     </DatiTrasmissione>
        //   </FatturaElettronicaHeader>

        Xml xml = new Xml();
        xml.setTag("FatturaElettronicaHeader");
        xml.updateChildContent("DatiTrasmissione|IdTrasmittente|IdPaese", "IT");
        xml.updateChildContent("DatiTrasmissione|IdTrasmittente|IdCodice", "12345678");

        // Now insert a new node to get this XML:

        //   <FatturaElettronicaHeader>
        //     <DatiTrasmissione>
        //       <IdTrasmittente>
        //         <IdPaese>IT</IdPaese>
        //         <NewTag>Content</NewTag>
        //         <IdCodice>12345678</IdCodice>
        //       </IdTrasmittente>
        //     </DatiTrasmissione>
        //   </FatturaElettronicaHeader>

        Xml xT = xml.findChild("DatiTrasmissione|IdTrasmittente");
        int index = xT.tagIndex("IdPaese");
        if (index < 0) {
            System.out.println("nothing found at the given tag.");
            return;
        }

        Xml x1 = xT.newChildAfter(index, "NewTag", "Content");
        x1.close();
        xT.close();

        // Show the resulting XML.
        System.out.println(xml.getXml());
    }
}