Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static void main(String argv[]) {
- try {
- DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
- DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
- // root elements
- Document doc = docBuilder.newDocument();
- Element rootElement = doc.createElement("heroes_data");
- doc.appendChild(rootElement);
- // staff elements
- Element staff = doc.createElement("hero");
- rootElement.appendChild(staff);
- // set attribute to staff element
- //Attr attr = doc.createAttribute("id");
- //attr.setValue("1");
- //staff.setAttributeNode(attr);
- // shorten way
- // staff.setAttribute("id", "1");
- // firstname elements
- Element firstname = doc.createElement("firstname");
- firstname.appendChild(doc.createTextNode("artem"));
- staff.appendChild(firstname);
- // age elements
- Element salary = doc.createElement("age");
- salary.appendChild(doc.createTextNode("18"));
- staff.appendChild(salary);
- // write the content into xml file
- TransformerFactory transformerFactory = TransformerFactory.newInstance();
- Transformer transformer = transformerFactory.newTransformer();
- DOMSource source = new DOMSource(doc);
- //StreamResult result = new StreamResult(new File("C:\file.xml"));
- // Output to console for testing
- StringWriter writer = new StringWriter();
- StreamResult result = new StreamResult(writer);
- transformer.transform(source, result);
- String strResult = writer.toString();
- FileOutputStream out=new FileOutputStream("base");
- BufferedOutputStream bos = new BufferedOutputStream(out);
- // перевод строки в байты
- byte[] buffer = strResult.getBytes();
- bos.write(buffer, 0, buffer.length);
- out.close();
- System.out.println(strResult);
- } catch (ParserConfigurationException pce) {
- pce.printStackTrace();
- } catch (TransformerException tfe) {
- tfe.printStackTrace();
- } catch (IOException ex) {
- ex.printStackTrace();
- //System.out.println(ex.getMessage());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement