1

I have an Activity class, it has list of children subactivities, each of said subactivities have its own list and so on.

public class Activity 
{   
    private Activity parent;         
    private ArrayList<Activity> children = new ArrayList();
    private String name;  
}

Is there an efficent way to parse it into XML file that looks like something like this:

<Activity name="1">
<children>
   <Activity name="2>
   <children>
       <Activity name="3">
   </children>
</children>
<Activity name ="4">

and so on?

1
  • What you're looking for is serialization and there are several options for XML serialization, starting with JAXB: jaxb.java.net Commented May 3, 2017 at 21:06

1 Answer 1

1

The simplest method of serialization would be using an XMLStreamWriter. This assumes that your only goal is to take a POJO and convert it into an XML format as an endpoint, as opposed to if you're also taking it as an input, which would be more suited for a more complex model such as JAXB.

You'd instantiate the writer to a file, and then write away.

XMLStreamWriter writer; //instantiate this based on your output format, see the tutorial for example

Then you could use this recursive method to populate the XML.

public void writeActivity(Activity activity) {
    writer.writeStartElement("activity");
    writer.writeAttribute("name", activity.getName());

    writer.writeStartElement("children");
    for(Activity child : activity.getChildren()) {
        writeActivity(child);
    }
    writer.writeEndElement(); //ends element children

    writer.writeEndElement(); //ends element activity
}

Depending on if you want an empty "children" node, you can do an if statement, and so on.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! That's exactly what I'm looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.