如何在XML文件中构建多维数组?

时间:2011-03-15 14:52:00

标签: java xml arrays xml-serialization multidimensional-array

我有一个多维数组,例如:

String[][] greatCities = new String[2][2];
greatCities[0][0] = "Vancouver";
greatCities[0][1] = "Charlottetown";
greatCities[1][0] = "Zürich";
greatCities[1][1] = "Bern";

现在我正在寻找一种将结构(无代码)此数组保存到xml文件的好方法。我到目前为止的最佳解决方案是:

<GreatCities>
  <Item index0="0" index1="0">Vancouver</Item>
  <Item index0="0" index1="1">Charlottetown</Item>
  <Item index0="1" index1="0">Zürich</Item>
  <Item index0="1" index1="1">Bern</Item>
</GreatCities>

有没有人有更好的解决方案?

3 个答案:

答案 0 :(得分:7)

因为它实际上是一个数组数组......

<GreatCity index =0>
   <Name index="0">Vancouver</Name>
   <Name index="1">Charlottetown</Name>
</GreatCity>
etc...

答案 1 :(得分:2)

<GreatCities>
  <Items index="0">
    <Item index="0">Vancouver</Item>
    <Item index="1">Charlottetown</Item>
  </Items>
  <Items index="1">
    <Item index="0">Zürich</Item>
    <Item index="1">Bern</Item>
  </Items>
</GreatCities>

答案 2 :(得分:2)

你的解决方案可能足够紧凑,但我认为反序列化很复杂(例如从xml中检索数组)。实际上,您应该尽快知道数组的大小:要做到这一点,您必须扫描整个xml文档。 我更喜欢没有属性索引的有序结构:

<GreatCities>
  <GreatCity>
    <Name>Vancouver</Name>
    <Name>Charlottetown</Name>
  </GreatCity>
  <GreatCity />
  <GreatCity>
    <Name>Zürich</Name>
    <Name/>
    <Name>Bern</Name>
  </GreatCity>
</GreatCities>

在该示例中,我插入了两个空元素来指向并清空行/单元格。 此时,您可以通过填充锯齿状阵列来扫描xml文档。