Ive written some code that creates an XML file from my System Properties in java. It works exactly how I want it to but I really (really) dont like how I ended up just using like 5 if statements to get it to work since I noticed none of the properties go beyond 4 delimited substrings anyways. Id much prefer using an iterator and some kind of hasNext() method to continue appending onto elements until the end of the string but I couldn't work anything out. I couldn't find a way to append the newest tag onto the last one in a loop/ add the value to the end of the elements.
This is what I currently have as a quick fix to get the program running.
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("JAVA");
doc.appendChild(rootElement);
Iterator it = hm.entrySet().iterator();
while (it.hasNext())
{
Map.Entry entry = (Map.Entry) it.next();
String keyString = (String)entry.getKey();
String val = (String)entry.getValue();
java.util.List<String> sa = Arrays.asList(keyString.split("\\."));
Iterator ait = sa.iterator();
Element tag = doc.createElement((String) ait.next());
rootElement.appendChild(tag);
Element tag2 = null;
Element tag3 = null;
Element tag4 = null;
Element tag5 = null;
while(ait.hasNext())
{
if(ait.hasNext())
{
tag2 = doc.createElement((String)ait.next());
tag.appendChild(tag2);
if(!ait.hasNext())
tag2.appendChild(doc.createTextNode(val));
}
if(ait.hasNext())
{
tag3=doc.createElement((String)ait.next());
tag2.appendChild(tag3);
if(!ait.hasNext())
tag3.appendChild(doc.createTextNode(val));
}
if(ait.hasNext())
{
tag4=doc.createElement((String)ait.next());
tag3.appendChild(tag4);
if(!ait.hasNext())
tag4.appendChild(doc.createTextNode(val));
}
if(ait.hasNext())
{
tag5=doc.createElement((String)ait.next());
tag5.appendChild(tag5);
if(!ait.hasNext())
tag5.appendChild(doc.createTextNode(val));
}
}
}
Transformer transformer = null;
TransformerFactory transformerFactory = TransformerFactory.newInstance();
try
{
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("XMLtester"));
transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.transform(source, result);
} catch (TransformerConfigurationException e)
{
e.printStackTrace();
} catch (TransformerException e)
{
e.printStackTrace();
}
catch(NullPointerException e)
{
System.out.println("ERROR: " + e.toString());
}
System.out.println("File saved!");
If anyone has any ideas on how to make this a little more flexible or elegant so as to take in any number of delimited substrings id appreciate it.