java - 如何转换列表使用 XMLMapper (Jackson) 到 XML 对象?
问题描述
我有一个表示为List<String[]>
. 列表的第一个元素是标题,其他元素是一行。我不提前知道 List 的结构,所以创建一个包含属性/字段的类不是一个选项。
想象一下,我有一个如下所示的表(我们称之为“数据库”):
Age|Name|Sex
23 |John|Male
19 |Sam |Female
18 |Alex|Male
列表的第一个元素是一个字符串数组,看起来像这样:["Age", "Name", Sex"] 而行看起来像这样 ["23", "John", "Male"]
如何获得如下所示的 XML 输出:
<Table name="Database">
<Row name="1">
<Item name="Age">23</Item>
<Item name="Name">John</Item>
<Item name="Sex">Male</Item>
</Row>
<Row name="2">
<Item name="Age">19</Item>
<Item name="Name">Sam</Item>
<Item name="Sex">Female</Item>
</Row>
<Row name="3">
<Item name="Age">18</Item>
<Item name="Name">Alex</Item>
<Item name="Sex">Male</Item>
</Row>
基本上我收到了一个表格的输入,我运行我的算法并得到一个列表作为返回,第一个元素是标题。我尝试过使用 XMLMapper,它可以快速将其映射到 XML,但我没有得到我想要的格式/结构。
public String createXMLObject() throws IOException {
List<String[]> table = extractData(); //extractData() is my custom method
ObjectMapper mapper = new XmlMapper();
String result = mapper.writeValueAsString(table);
mapper.writeValue(new File("test.xml"), table);
System.out.println(result);
return result;
}
解决方案
不需要 Jackson 的开销,特别是因为无论如何您都必须先将数据转换为不同的格式。
只需使用 StAX,如下所示:
List<String[]> table = Arrays.asList(
new String[] { "Age", "Name", "Sex" },
new String[] { "23" , "John", "Male" },
new String[] { "19" , "Sam" , "Female" },
new String[] { "18" , "Alex", "Male" } );
XMLStreamWriter xml = XMLOutputFactory.newFactory().createXMLStreamWriter(System.out);
xml.writeStartElement("Table");
xml.writeAttribute("name", "Database");
String[] header = table.get(0);
for (int rowNo = 1; rowNo < table.size(); rowNo++) {
String[] row = table.get(rowNo);
xml.writeCharacters(System.lineSeparator());
xml.writeStartElement("Row");
xml.writeAttribute("name", String.valueOf(rowNo));
for (int colIdx = 0; colIdx < header.length; colIdx++) {
xml.writeCharacters(System.lineSeparator() + " ");
xml.writeStartElement("Item");
xml.writeAttribute("name", header[colIdx]);
xml.writeCharacters(row[colIdx]);
xml.writeEndElement(); // </Item>
}
xml.writeCharacters(System.lineSeparator());
xml.writeEndElement(); // </Row>
}
xml.writeCharacters(System.lineSeparator());
xml.writeEndElement(); // </Table>
xml.close();
输出
<Table name="Database">
<Row name="1">
<Item name="Age">23</Item>
<Item name="Name">John</Item>
<Item name="Sex">Male</Item>
</Row>
<Row name="2">
<Item name="Age">19</Item>
<Item name="Name">Sam</Item>
<Item name="Sex">Female</Item>
</Row>
<Row name="3">
<Item name="Age">18</Item>
<Item name="Name">Alex</Item>
<Item name="Sex">Male</Item>
</Row>
</Table>
推荐阅读
- javascript - 循环用户输入和添加骰子的总和
- html - 我有一个 div 部分,里面有 3 个 div 项,我希望它们使用 html css 均匀分布
- handlebars.js - 如何使用外壳中的车把?
- python - 如何从日记条目中制作字典?
- javascript - javascript中2个src的比较
- c++ - Visual Studio 2019 的 OpenCV 错误和警告
- vue.js - Vue v-for 组件中的数据问题
- c# - 如何在我的 asp.net core 3.1 应用程序中播种用户和角色?
- vue.js - Vuejs引导b表数据未加载/更新
- python - 我怎样才能设法在这个最短路径问题中获得请求的输出?