Advertisement
Guest User

Untitled

a guest
Oct 24th, 2016
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.38 KB | None | 0 0
  1. package ua.inf.smart.create_xml;
  2.  
  3. import org.w3c.dom.Attr;
  4. import org.w3c.dom.Document;
  5. import org.w3c.dom.Element;
  6.  
  7. import javax.xml.parsers.DocumentBuilder;
  8. import javax.xml.parsers.DocumentBuilderFactory;
  9. import javax.xml.parsers.ParserConfigurationException;
  10. import javax.xml.transform.Transformer;
  11. import javax.xml.transform.TransformerConfigurationException;
  12. import javax.xml.transform.TransformerException;
  13. import javax.xml.transform.TransformerFactory;
  14. import javax.xml.transform.dom.DOMSource;
  15. import javax.xml.transform.stream.StreamResult;
  16. import java.io.File;
  17.  
  18. public class Main {
  19. public static void main(String[] args) throws ParserConfigurationException, TransformerException {
  20. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  21. DocumentBuilder builder = factory.newDocumentBuilder();
  22. Document doc = builder.newDocument();
  23.  
  24. String fileToPath = "src/ua/inf/smart/create_xml/exmpl.xml";
  25.  
  26. Element root = doc.createElement("root");
  27. doc.appendChild(root);
  28.  
  29. Element section = doc.createElement("section");
  30. Attr sectionId = doc.createAttribute("id");
  31. sectionId.setValue("1234");
  32. section.setAttributeNode(sectionId);
  33. root.appendChild(section);
  34.  
  35. Element position = doc.createElement("position");
  36. Attr positionId = doc.createAttribute("id");
  37. positionId.setValue("56");
  38. position.setAttributeNode(positionId);
  39. section.appendChild(position);
  40.  
  41. Element title = doc.createElement("title");
  42. title.appendChild(doc.createTextNode("Product_1"));
  43. position.appendChild(title);
  44.  
  45. Element price = doc.createElement("price");
  46. price.appendChild(doc.createTextNode("20000"));
  47. position.appendChild(price);
  48.  
  49. Element amount = doc.createElement("amount");
  50. amount.appendChild(doc.createTextNode("153"));
  51. Attr amountType = doc.createAttribute("type");
  52. amountType.setValue("pcs");
  53. amount.setAttributeNode(amountType);
  54. position.appendChild(amount);
  55.  
  56.  
  57. TransformerFactory tf = TransformerFactory.newInstance();
  58. Transformer transformer = tf.newTransformer();
  59. DOMSource domSource = new DOMSource(doc);
  60. StreamResult streamResult = new StreamResult(new File(fileToPath));
  61. transformer.transform(domSource, streamResult);
  62.  
  63. System.out.println("Document has saved");
  64. }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement