我正在尋找一個Java庫,它可以採用XSD架構並創建一個示例XML文檔,然後可以對其進行操作。在我的簡單例子中,我給了一個XML,我加載,操作和打印。我如何才能達到相同的結果,如果我只有一個XSD?在Java中使用XSD創建XML文檔的實例
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<ns0:store_msg xmlns:ns0=\"http://data\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://data sample.xsd \">" +
"<item>" +
"<name>A</name>" +
"<price>1.1</price>" +
"</item>" +
"<item>" +
"<name>B</name>" +
"<price>2.2</price>" +
"</item>" +
"</ns0:store_msg>";
// 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")));
你應該使用JAXB:https://github.com/javaee/jaxb-v2 –
同意 - 使用JAXB。 https://dzone.com/articles/introduction-to-jaxb-20 –
感謝您的回覆。我對使用JAXB有點困惑。請回答新手問題,但JAXB會在運行時之外生成POJO的源代碼,然後可以編譯和使用這個非編組代碼,或者JAXB可以基於給出的架構在運行時實際創建對象,並且可以操作和編組此對象到原始的XML中,讓我們說,一個文件? – VilleLipponen