Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7844705
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 2, 20262026-06-02T16:58:20+00:00 2026-06-02T16:58:20+00:00

I am reading an XML file using Stax parser and writing it using DOM

  • 0

I am reading an XML file using Stax parser and writing it using DOM in java. I am not getting desired XML output. I read following XML file

<config>

    <Sensor1>
       <name>abc</name>
       <range>100</range>
    </Sensor1>

   <sensor2>
       <name>xyz</name>
       <range>100</range>
   </sensor2>

</config>

I parse the above XML file using Stax parser as follows

public void readConfig(String configFile) {
boolean sensor1 = false;
boolean sensor2 = false;

try
{
  XMLInputFactory inputFactory = XMLInputFactory.newInstance();
  InputStream in = new FileInputStream(configFile);
  XMLEventReader eventReader = inputFactory.createXMLEventReader(in);

  // Read the XML document
 while (eventReader.hasNext()) {
    XMLEvent event = eventReader.nextEvent();

    if (event.isStartElement()) {

         StartElement startElement = event.asStartElement();

                if (startElement.getName().getLocalPart() == (sensor1)) {

                   sensor1 = true;
                   Sensor1 Obj1 = new Sensor1();                         
        }

            if (startElement.getName().getLocalPart() == (sensor2)) {

                        sensor2 = true;
                        Sensor2 Obj2 = new Sensor2();

                }



     if (sensor1) {

      if (event.asStartElement().getName().getLocalPart().equals(name)) {

             event = eventReader.nextEvent();
                     Obj1.set_Sensor_Name(event.asCharacters().getData());
             continue;
         }


      if (event.asStartElement().getName().getLocalPart().equals(range)) {

             event = eventReader.nextEvent();
                     Obj1.set_Sensor_Range(event.asCharacters().getData());
             continue;
         }
     }


 if (sensor2) {

   if (event.asStartElement().getName().getLocalPart().equals(name)) {
             event = eventReader.nextEvent();
             Obj2.set_Sensor_Name(event.asCharacters().getData());
             continue;
       }

       if (event.asStartElement().getName().getLocalPart().equals(range)) {

             event = eventReader.nextEvent();
                     Obj1.set_Sensor_Range(event.asCharacters().getData());
             continue;
         }


  }

 if (event.isEndElement()) {
        EndElement endElement = event.asEndElement();     
        if (endElement.getName().getLocalPart() == (sensor1)) {

                   sensor1.addToArray();
         }

        if (endElement.getName().getLocalPart() == (sensor2)) {

                    sensor2.addToArray();

        }
       }
     }

In “Sensor1” and “Sensor2” class I am adding extra information depending on some condition.

class Sensor1 {

  public ArrayList<Object> list = new ArrayList<Object>();
  String name;
  double range;

  public void set_Sensor_Name(String name) {
  this.name = name;

  }

  public void set_Sensor_Range(double range) {
  this.range = range;

  }

  public void addToArray(){
    double distance =50;

     if(distance<range){
       list.add("TITANIC");
       list.add(123456);
     }

     WriteFile fileObj = new WriteFile();
     fileObj.writeXMlFile(list);

  }

} 

This is the class to write the XML

public class WriteFile {

public void writeXmlFile(ArrayList<Object> list) {

try {

    DocumentBuilderFactory dFact = DocumentBuilderFactory.newInstance();
    DocumentBuilder build = dFact.newDocumentBuilder();
    Document doc = build.newDocument();

    Element root = doc.createElement("SensorTracks");
    doc.appendChild(root);

    Element sensorInfo = doc.createElement("SensorDetails");
    root.appendChild(sensorInfo);

    Element vesselInfo = doc.createElement("VesselDetails");
    root.appendChild(vesselInfo);


    for(int i=0; i<list.size(); i +=4 ) {

        Element name = doc.createElement("SensorName");
        name.appendChild(doc.createTextNode(String.valueOf(list.get(i))));
        sensorInfo.appendChild(name);

        Element range = doc.createElement("SensorRange");
        name.appendChild(doc.createTextNode(String.valueOf(list.get(i+1))));
        sensorInfo.appendChild(range);

        Element mmi = doc.createElement("shipname");
        mmi.appendChild(doc.createTextNode(String.valueOf(list.get(i+2))));
        vesselInfo.appendChild(mmi);

        Element license = doc.createElement("license");
        license.appendChild(doc.createTextNode(String.valueOf(list.get(i+3))));
        vesselInfo.appendChild(license); 

    }


     // Save the document to the disk file
    TransformerFactory tranFactory = TransformerFactory.newInstance();
    Transformer aTransformer = tranFactory.newTransformer();

    // format the XML nicely
    aTransformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");

    aTransformer.setOutputProperty(
            "{http://xml.apache.org/xslt}indent-amount", "4");
    aTransformer.setOutputProperty(OutputKeys.INDENT, "yes");



    DOMSource source = new DOMSource(doc);
    try {
        FileWriter fos = new FileWriter("/home/ros.xml");
        StreamResult result = new StreamResult(fos);
        aTransformer.transform(source, result);

    } catch (IOException e) {

        e.printStackTrace();
    }



} catch (TransformerException ex) {
    System.out.println("Error outputting document");

} catch (ParserConfigurationException ex) {
    System.out.println("Error building document");
}

When I execute, I get following XML

<SensorTracks>        
   <sensorDetails>
     <SensorName>xyz</SensorName>
     <SensorRange>100</SensorRange>
   </sensorDetails>
 <VesselDetails>
      <shipname>TITANIC</shipname>
      <license>123456</license>
</vesselDetails>

MY FINAL OUTPUT MUST BE

<config>

<SensorTracks>        
   <sensorDetails>
     <SensorName>xyz</SensorName>
     <SensorRange>100</SensorRange>
     <SensorName>abc</SensorName>
     <SensorRange>100</SensorRange> 
   </sensorDetails>
 <VesselDetails>
      <shipname>TITANIC</shipname>
      <license>123456</license>
</vesselDetails>

What wrong thing I am I doing in my code ?? Any help is appreciated. Thanks in advance

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-02T16:58:21+00:00Added an answer on June 2, 2026 at 4:58 pm

    I am answering my own question again. The problem is very simple. To get the desired output as mention above. just make the following changes to “WriteFile” class.

    FileWriter fos = new FileWriter("/home/ros.xml" ,true);
    

    Finally, I am learning Java 🙂

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm reading a large xml file using HttpURLConnection in java as follows. StringBuilder responseBuilder
I'm reading XML file using Etree module. Im using following code to print the
I am reading an xml file using javascript and then I need to submit
I'm reading an xml file using Jaxb, now the contents of the xml file
I'm using Qt C++ and am reading in an XML file for data. I
While implementing XML file reading/writing in my application I saw that when I call
what is the best way of reading xml file using linq and the below
I am reading an XML file using an XMLTextReader. Is there a way to
I am trying to create a dynamic menu by reading an XML file using
I have a problem reading OWL/XML files from Java using Jena. I have no

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.