簡體   English   中英

Java:根據用戶定義的XSD編寫XML

[英]Java: write XML according to user defined XSD

我正在編寫一個工具來將CSV格式的數據轉換為XML。 用戶將指定解析方法,即:輸出的XSD,CSV中的哪個字段位於生成的XML的哪個字段中。

(非常簡化的用例)示例:

CSV

Ciccio;Pippo;Pappo
1;2;3

XSD

(more stuff...)
<xs:element name="onetwo">
<xs:element name="three">
<xs:element name="four">

用戶提供規則

   Ciccio -> onetwo
   Pippo -> three
   Pappo -> four

我使用數據集在C#中實現了這個,我怎么能用Java做呢? 我知道有DOM,JAXB等,但似乎XSD僅用於驗證否則創建的XML。 我錯了嗎?

編輯:一切都需要在運行時。 我不知道我會收到什么樣的XSD,所以我不能實例化不存在的對象,也不能用數據填充它們。 所以我猜測xjc不是一個選項。

由於您具有輸出XML文件的XSD ,因此創建此XML的最佳方法是使用Java Architecture for XML Binding(JAXB)。 您可能需要參考: “使用JAXB”教程,向您概述如何根據您的要求使用它。

基本思路如下:

  • 從XML模式生成JAXB Java類,即您擁有的XSD
  • 使用模式派生的JAXB類在Java應用程序中解組和編組XML內容
  • 使用模式派生的JAXB類從頭開始創建Java內容樹
  • 將數據解組到輸出XML文件。

這是另一個你可能會發現信息的教程

這仍然在進行中,但是當您在新文檔樹中找到它們時,您可以通過XSD寫出元素。

public void run() throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse(new InputSource(new FileReader(
            "schema.xsd")));

    Document outputDoc = builder.newDocument();

    recurse(document.getDocumentElement(), outputDoc, outputDoc);

    TransformerFactory transFactory = TransformerFactory.newInstance();
    Transformer transformer = transFactory.newTransformer();
    StringWriter buffer = new StringWriter();
    transformer.transform(new DOMSource(outputDoc),
            new StreamResult(buffer));
    System.out.println(buffer.toString());
}

public void recurse(Node node, Node outputNode, Document outputDoc) {

    if (node.getNodeType() == Node.ELEMENT_NODE) {
        Element element = (Element) node;
        if ("xs:element".equals(node.getNodeName())) {
            Element newElement = outputDoc.createElement(element
                    .getAttribute("name"));
            outputNode = outputNode.appendChild(newElement);

           // map elements from CSV values here?
        }
        if ("xs:attribute".equals(node.getNodeName())) {
           //TODO required attributes
        }
    }
    NodeList list = node.getChildNodes();
    for (int i = 0; i < list.getLength(); i++) {
        recurse(list.item(i), outputNode, outputDoc);
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM