1

我正在编写一个将 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

我已经使用 Dataset 在 C# 中实现了这个,我怎么能在 Java 中做到这一点?我知道有 DOM、JAXB 等,但似乎 XSD 仅用于验证以其他方式创建的 XML。我错了吗?

编辑:一切都需要在运行时。我不知道我会收到什么样的 XSD,所以我不能实例化不存在的对象,也不能用数据填充它们。所以我猜xjc不是一个选择。

4

2 回答 2

3

由于您有XSD输出XML文件,因此创建此文件的最佳方法XML是使用 Java Architecture for XML Binding (JAXB)。您可能需要参考:“使用 JAXB”教程,以概述如何使用它来满足您的需求。

基本思路如下:

  • 从 XML 模式生成 JAXB Java 类,即XSD您拥有的
  • 使用模式派生的 JAXB 类在 Java 应用程序中解组和编组 XML 内容
  • 使用模式派生的 JAXB 类从头开始创建 Java 内容树
  • 将数据解组到输出XML文件。

这是另一个您可能会发现信息丰富的教程。

于 2012-09-01T18:04:49.110 回答
0

这仍在进行中,但您可以在 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);
    }

}
于 2012-09-02T10:03:20.710 回答