java 如何在 XML 文件中构造多维数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5313522/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to structure a multi-dimensional array in a XML file?
提问by Thomas Zuberbühler
I have a multi-dimensional array such as:
我有一个多维数组,例如:
String[][] greatCities = new String[2][2];
greatCities[0][0] = "Vancouver";
greatCities[0][1] = "Charlottetown";
greatCities[1][0] = "Zürich";
greatCities[1][1] = "Bern";
Now I'm looking for a good way to save the structure(no code) this array to a xml file. Best solution I have so far is:
现在我正在寻找一种将这个数组的结构(无代码)保存到 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>
Does anyone have a better solution?
有没有人有更好的解决方案?
回答by Euclid
As its effectively an array of arrays...
因为它实际上是一个数组数组......
<GreatCity index =0>
<Name index="0">Vancouver</Name>
<Name index="1">Charlottetown</Name>
</GreatCity>
etc...
回答by Thomas Zuberbühler
<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>
回答by Mario Vernari
Your solution may be compact enough, but I think is complicated for the deserialization (e.g. retrieve the array from the xml). In fact, you should know as soon what is the size of the array: to do that you must scan the whole xml document. I'd rather prefer a structure ordered, without attribute indexes:
您的解决方案可能足够紧凑,但我认为反序列化很复杂(例如从 xml 中检索数组)。事实上,您应该尽快知道数组的大小:为此您必须扫描整个 xml 文档。我更喜欢没有属性索引的有序结构:
<GreatCities>
<GreatCity>
<Name>Vancouver</Name>
<Name>Charlottetown</Name>
</GreatCity>
<GreatCity />
<GreatCity>
<Name>Zürich</Name>
<Name/>
<Name>Bern</Name>
</GreatCity>
</GreatCities>
In that sample I have inserted two empty elements to point and empty row/cell. At this point, you may scan the xml document by filling the jagged array.
在那个示例中,我插入了两个空元素来指向和空行/单元格。此时,您可以通过填充锯齿状数组来扫描 xml 文档。