hi
when i run the below program i got output like this
?xml version = '1.0'?>
<Products>
<Product/>
<ProductName>sugar</ProductName>
<Price>242</Price>
<Product/>
<ProductName>mint</ProductName>
<Price>4764</Price>
</Products>
but i want output like this
<?xml version = '1.0'?>
<Products>
<Product>
<ProductName>sugar</ProductName>
<Price>242</Price>
</Product>
<Product>
<ProductName>mint</ProductName>
<Price>4764</Price>
</Product>
</Products>
what changes should i made to the program to get o/p like above xml,;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.*;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.StringWriter;
import java.io.IOException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
public class CreateUsingDom {
public static void saveDocAsFile(Document
doc,
String fname) {
try {
TransformerFactory tfFac = TransformerFactory.newInstance();
// use null trandformation
Transformer tf = tfFac.newTransformer();
tf.setOutputProperty(OutputKeys.INDENT,"yes");
tf.transform(new DOMSource(doc), new StreamResult(System.out));
}
/* catch (IOException ioe) {
ioe.printStackTrace();
}*/
catch (TransformerException e) {
e.printStackTrace();
}
}
public static String returnDocAsString(Document doc) {
StringWriter sw = new StringWriter();
try {
TransformerFactory tfFac = TransformerFactory.newInstance();
// use null trandformation
Transformer tf = tfFac.newTransformer();
tf.transform(new DOMSource(doc), new StreamResult(sw));
}
catch (TransformerException e) {
e.printStackTrace();
}
return sw.toString();
}
public static void main(String[] args) {
String fname="t.xml";
DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = fac.newDocumentBuilder();
Document doc = db.newDocument();
//-------------------------------
Element rt = doc.createElement("Products");
doc.appendChild(rt);
String main[]={"Product","Product"};
String productnames[]={"ProductName","ProductName"};
String product[]={"sugar","mint"};
String price[]={"Price","Price"};
String priceValues[]={"242","4764"};
for(int i=0;i<productnames.length;i++){
Element main1 = doc.createElement(main[i]);
Element productnames1 = doc.createElement(productnames[i]);
Text product1 = doc.createTextNode(product[i]);
Element price1 = doc.createElement(price[i]);
Text priceValues1 = doc.createTextNode(priceValues[i]);
productnames1.appendChild(product1);
price1.appendChild(priceValues1);
rt.appendChild(main1);
rt.appendChild(productnames1);
rt.appendChild(price1);
}
saveDocAsFile(doc,fname);
}
catch (ParserConfigurationException e) {
e.printStackTrace();
}
}
}
bye
chaitanya