Advertisement
Guest User

Untitled

a guest
Feb 22nd, 2019
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.02 KB | None | 0 0
  1. public static void main(String argv[]) {
  2.  
  3. try {
  4.  
  5. DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
  6. DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
  7.  
  8. // root elements
  9. Document doc = docBuilder.newDocument();
  10. Element rootElement = doc.createElement("heroes_data");
  11. doc.appendChild(rootElement);
  12.  
  13. // staff elements
  14. Element staff = doc.createElement("hero");
  15. rootElement.appendChild(staff);
  16.  
  17. // set attribute to staff element
  18. //Attr attr = doc.createAttribute("id");
  19. //attr.setValue("1");
  20. //staff.setAttributeNode(attr);
  21.  
  22. // shorten way
  23. // staff.setAttribute("id", "1");
  24.  
  25. // firstname elements
  26. Element firstname = doc.createElement("firstname");
  27. firstname.appendChild(doc.createTextNode("artem"));
  28. staff.appendChild(firstname);
  29.  
  30. // age elements
  31. Element salary = doc.createElement("age");
  32. salary.appendChild(doc.createTextNode("18"));
  33. staff.appendChild(salary);
  34.  
  35. // write the content into xml file
  36. TransformerFactory transformerFactory = TransformerFactory.newInstance();
  37. Transformer transformer = transformerFactory.newTransformer();
  38. DOMSource source = new DOMSource(doc);
  39.  
  40. //StreamResult result = new StreamResult(new File("C:\file.xml"));
  41.  
  42. // Output to console for testing
  43.  
  44. StringWriter writer = new StringWriter();
  45. StreamResult result = new StreamResult(writer);
  46. transformer.transform(source, result);
  47. String strResult = writer.toString();
  48.  
  49. FileOutputStream out=new FileOutputStream("base");
  50. BufferedOutputStream bos = new BufferedOutputStream(out);
  51. // перевод строки в байты
  52. byte[] buffer = strResult.getBytes();
  53. bos.write(buffer, 0, buffer.length);
  54. out.close();
  55.  
  56. System.out.println(strResult);
  57.  
  58. } catch (ParserConfigurationException pce) {
  59. pce.printStackTrace();
  60. } catch (TransformerException tfe) {
  61. tfe.printStackTrace();
  62. } catch (IOException ex) {
  63. ex.printStackTrace();
  64. //System.out.println(ex.getMessage());
  65. }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement