Addy
Addy

Reputation: 427

XML File not getting looped Through Out

I am struck with this code I have a huge xml file which contains various "servers","port" tags which needs to be updated . When I execute the below code only the first.server and port number gets updated it doesn't loop through entire code and change all port and server tags I am not getting any error but unable to loop through the code:

import java.io.File;
import java.io.IOException;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import org.w3c.dom.*;
import org.xml.sax.SAXException;    
public class XMLFile {        
    public static final String xmlFilePath ="C:\\Users\\c200433\\Desktop\\Kommu234.twb";        
    public static void main(String argv[]) {        
        try {        
            DocumentBuilderFactory documentBuilderFactory =         DocumentBuilderFactory.newInstance();    
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();    
            Document document = documentBuilder.parse(xmlFilePath);    
            Node employee = document.getElementsByTagName("connection").item(0);    
            NamedNodeMap attribute = employee.getAttributes();
            Node nodeAttr = attribute.getNamedItem("server");
            nodeAttr.setTextContent("aventador.a:1530");
            Node nodeAttr1 = attribute.getNamedItem("service");
            Node nodeAttr2 = attribute.getNamedItem("port");
             nodeAttr1.setTextContent("tst806");
              nodeAttr2.setTextContent(""); // Value is correct but doesnt get looped through                                       
            TransformerFactory transformerFactory = TransformerFactory.newInstance();

            Transformer transformer = transformerFactory.newTransformer();
            DOMSource domSource = new DOMSource(document);

            StreamResult streamResult = new StreamResult(new File(xmlFilePath));                  transformer.transform(domSource, streamResult);

            System.out.println("The XML File was ");    
        } catch (ParserConfigurationException pce) {
            pce.printStackTrace();
        } catch (TransformerException tfe) {
            tfe.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } catch (SAXException sae) {
            sae.printStackTrace();
        }
    }
}

Upvotes: 0

Views: 38

Answers (1)

Cody S
Cody S

Reputation: 4824

On the line Node employee = document.getElementsByTagName("connection").item(0);, you are only getting one Node.

If you, instead, do

NodeList employees = document.getElementsByTagName("connection");
for(int i = 0; i < employees.getLength(); i++) {
    Node employee = employees.item(i);
    ....
}

You should iterate over them.

Upvotes: 1

Related Questions