我正在编写一个工具,将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不是一个选项。
答案 0 :(得分:3)
由于您的输出XSD
文件有XML
,因此创建此XML
的最佳方法是使用Java Architecture for XML Binding(JAXB)。您可能需要参考:"Using JAXB"教程,向您概述如何根据您的要求使用它。
基本思路如下:
XSD
XML
文件。Here's another tutorial您可能会发现信息丰富。
答案 1 :(得分: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);
}
}