title: Create instance of XML document using XSD in Java
body: <p>I am looking for a Java library that can take an XSD schema and create a sample XML document that can then be manipulated. In my simple example i am given an XML that i load, manipulate and print. How can i achieve the same result if i am only given an XSD?</p>
  
  <pre><code>String xml = "&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;" + 
                  "&lt;ns0:store_msg xmlns:ns0=\"http://data\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://data sample.xsd \"&gt;" + 
                  "&lt;item&gt;" +
                  "&lt;name&gt;A&lt;/name&gt;" +
                  "&lt;price&gt;1.1&lt;/price&gt;" +
                  "&lt;/item&gt;" +
                  "&lt;item&gt;" +
                  "&lt;name&gt;B&lt;/name&gt;" +
                  "&lt;price&gt;2.2&lt;/price&gt;" +
                  "&lt;/item&gt;" +
                  "&lt;/ns0:store_msg&gt;";
  
      // load XML
      DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder builder = builderFactory.newDocumentBuilder();
      Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes()));
  
  
      // manipulate XML
      Node root = doc.getFirstChild();
      Element el = doc.createElement("item");
      Element name = doc.createElement("name");
      Element price = doc.createElement("price");
      name.setTextContent("C");
      price.setTextContent("2.2");
      el.appendChild(name);
      el.appendChild(price);
      root.appendChild(el);
  
      // print XML
      TransformerFactory tf = TransformerFactory.newInstance();
      Transformer transformer = tf.newTransformer();
      transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
      transformer.setOutputProperty(OutputKeys.METHOD, "xml");
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
      transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
  
      transformer.transform(new DOMSource(doc), 
           new StreamResult(new OutputStreamWriter(System.out, "UTF-8")));
  </code></pre>