![](/img/trans.png)
[英]Unmarshalling, xml to java, invalid enum values are getting ignored that are not defined in XSD
[英]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不是一個選項。
這仍然在進行中,但是當您在新文檔樹中找到它們時,您可以通過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.