java - How to create multi level xml file -


i have trouble in finding info creating multi level tags in xml file example want next structure

<usercards>   <usercard usercardid="171">    <username>somename</username>    <usersurname>somesurname</usersurname>    <userage>24</userage>    <useradress>someadress</useradress>    <userphone>223334455</userphone>      <currentbooks>        <booname>somebookname</bookname>      </currentbooks>   </usercard> </usercards> 

i can create simple 1 level xml how can add new one?

 documentbuilderfactory docfactory = documentbuilderfactory.newinstance();                 documentbuilder docbulder = docfactory.newdocumentbuilder();                  //root mainelement                 document doc = docbulder.newdocument();                 element rootelement = doc.createelement("usercards");                 doc.appendchild(rootelement);                  //root book                 element usercard = doc.createelement("usercard");                 rootelement.appendchild(usercard);                 ...                   ...                 //write in xmlfile                 transformerfactory transformerfactory = transformerfactory.newinstance();                 transformer transformer = transformerfactory.newtransformer();                 domsource source = new domsource(doc);                 streamresult result = new streamresult(new file("test/usercards.xml")); 

seems me answered yourself.... can append elements element, not root. create elements calling doc.createelement("name") , append parent element of choice:

elmenet username = doc.createelement("username"); text usernametext = doc.createtextnode("somename"); username.appendchild(usernametext); usercard.appendchild(username); 

Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

c# - Get rid of xmlns attribute when adding node to existing xml -