Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ua.inf.smart.create_xml;
- import org.w3c.dom.Attr;
- import org.w3c.dom.Document;
- import org.w3c.dom.Element;
- import javax.xml.parsers.DocumentBuilder;
- import javax.xml.parsers.DocumentBuilderFactory;
- import javax.xml.parsers.ParserConfigurationException;
- import javax.xml.transform.Transformer;
- import javax.xml.transform.TransformerConfigurationException;
- import javax.xml.transform.TransformerException;
- import javax.xml.transform.TransformerFactory;
- import javax.xml.transform.dom.DOMSource;
- import javax.xml.transform.stream.StreamResult;
- import java.io.File;
- public class Main {
- public static void main(String[] args) throws ParserConfigurationException, TransformerException {
- DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
- DocumentBuilder builder = factory.newDocumentBuilder();
- Document doc = builder.newDocument();
- String fileToPath = "src/ua/inf/smart/create_xml/exmpl.xml";
- Element root = doc.createElement("root");
- doc.appendChild(root);
- Element section = doc.createElement("section");
- Attr sectionId = doc.createAttribute("id");
- sectionId.setValue("1234");
- section.setAttributeNode(sectionId);
- root.appendChild(section);
- Element position = doc.createElement("position");
- Attr positionId = doc.createAttribute("id");
- positionId.setValue("56");
- position.setAttributeNode(positionId);
- section.appendChild(position);
- Element title = doc.createElement("title");
- title.appendChild(doc.createTextNode("Product_1"));
- position.appendChild(title);
- Element price = doc.createElement("price");
- price.appendChild(doc.createTextNode("20000"));
- position.appendChild(price);
- Element amount = doc.createElement("amount");
- amount.appendChild(doc.createTextNode("153"));
- Attr amountType = doc.createAttribute("type");
- amountType.setValue("pcs");
- amount.setAttributeNode(amountType);
- position.appendChild(amount);
- TransformerFactory tf = TransformerFactory.newInstance();
- Transformer transformer = tf.newTransformer();
- DOMSource domSource = new DOMSource(doc);
- StreamResult streamResult = new StreamResult(new File(fileToPath));
- transformer.transform(domSource, streamResult);
- System.out.println("Document has saved");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement