How to make XML document from string in java or Android? -
i trying create dynamically generated xml file java. code trying use:
try{ bufferedreader bf = new bufferedreader(new inputstreamreader(system.in)); system.out.println("how many elements: "); string str = bf.readline(); int no = integer.parseint(str); system.out.println("enetr root: "); string root = bf.readline(); documentbuilderfactory dbf = documentbuilderfactory.newinstance(); documentbuilder db = dbf.newdocumentbuilder(); document d1 = db.newdocument(); element e1 = d1.createelement(root); d1.appendchild(e1); (int = 0; < no; i++) { system.out.println("enter element: "); string element = bf.readline(); system.out.println("enter data: "); string data = bf.readline(); element em = d1.createelement(element); em.appendchild(d1.createtextnode(data)); e1.appendchild(em); } transformerfactory tf = transformerfactory.newinstance(); transformer transformer = tf.newtransformer(); domsource source = new domsource(d1); file file = new file("src\\xml\\copy.xml"); system.out.println(file); if(!file.exists()){ file.createnewfile(); } outputstream outputstream = new fileoutputstream(file); streamresult result = new streamresult(outputstream); transformer.transform(source, result); outputstream.close(); }catch (exception e) { // todo: handle exception e.printstacktrace(); system.out.println("file not created"); }
this code works well. have string such:
string xmlrecords = "<data><terminal_id>1000099999</terminal_id><merchant_id>10004444</merchant_id><merchant_info>mc donald's - abdoun</merchant_info></data>";
i want create .xml
file xmlrecords
variable. how do this?
you can parse xml string document
this:
string xmlrecords = "<data><terminal_id>1000099999</terminal_id><merchant_id>10004444</merchant_id><merchant_info>mc donald's - abdoun</merchant_info></data>"; documentbuilderfactory factory = documentbuilderfactory.newinstance(); documentbuilder builder = factory.newdocumentbuilder(); document d1 = builder.parse(new inputsource(new stringreader(xmlrecords)));
you can keep file writing part mentioned in question, replace creation of document
instance above code.
Comments
Post a Comment