首页 > 解决方案 > 如何转换列表使用 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;
}

标签: javaxmljackson

解决方案


不需要 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>

推荐阅读