我会制作一个简单的转换器来获得真正的 XML 结构。解决方案的复杂性取决于您拥有的源文本。
这是我的实现。
假设您的分层数据结构良好,并且每个元素之前都有一定数量的空格。就我而言,我使用 4 个空格作为一级转换。
我从一个文本文件加载数据,如下所示:
Asia
India
Chennai
TN
Category1
Product1
100
Mumbai
MH
Category2
Product2
200
Category3
Product3
300
Product4
400
然后我遍历每个字符串并分析其级别。生成的树如下所示:
// 应用
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
minWidth="955" minHeight="600" creationComplete="init(event)">
<fx:Script>
<![CDATA[
import mx.events.FlexEvent;
private const SPACEDELIMITER:int = 4;
private var loader:URLLoader;
private var ar:Array = new Array();
[Bindable]private var data:XML = <Root/>;
private var inputStr:String;
protected function init(event:FlexEvent):void
{
loader = new URLLoader(new URLRequest("com/treexml/tree.txt"));
loader.dataFormat = URLLoaderDataFormat.TEXT;
loader.addEventListener(Event.COMPLETE, completeHandler);
}
private function completeHandler(event:Event):void
{
inputStr = URLLoader(event.target).data;
parseString();
}
private function parseString():void
{
var levels:Array = new Array();
ar = inputStr.split("\r\n");
var reg:RegExp = /[a-z0-9]/gi;
var globalShift:int = String(ar[0]).search(reg);
for (var i:int = 0; i < ar.length; i++)
{
var item:String = ar[i];
var shift:int = item.search(reg); //amount of witespaces before the text
var level:int = (shift - globalShift)/SPACEDELIMITER; //level of the node
var label:String = item.substring(shift, item.length);
levels[level] = i; //id of the last element for the given level
var node:XML = new XML();
node = <child id = {i} label = {label}/>;
if (level == 0)
data.appendChild(node);
else
data..child.(@id == levels[level - 1]).appendChild(node);
}
}
]]>
</fx:Script>
<mx:Tree width="250"
height="400"
dataProvider="{data.child}"
labelField="@label"/>
</s:Application>
//编辑
如果您的数据未通过空格对齐,请尝试使用其他版本的 parseString 函数。
假设您的数据如下所示:
Asia India Chennai TN Category1 Product1 100
Asia India Mumbai MH Category1 Product1 100
Asia India Calcutta CT Category1 Product1 100
Asia India Calcutta CT Category2 Product2 200
EMEA UK London LN Category3 Product1 123
EMEA UK London LN Category3 Product2 455
EMEA UK Reading RN Category1 Product1 500
EMEA UK Reading RN Category1 Product2 430
功能是:
private function parseString():void
{
ar = inputStr.split("\r\n");
var map:Dictionary = new Dictionary();
var delimiter:String = "***";
var id:int = 0;
for (var i:int = 0; i < ar.length; i++)
{
if(ar[i].length){//if it's not an empty string
var itemArray:Array = ar[i].replace(/\s{2,}/g, ' ').split(" ");//collapse multiple spaces as one using RegEx
var key:String = "";
var prevkey:String = "";
for (var j:int = 0; j< itemArray.length; j++)
{
prevkey = key;
key += itemArray[j] + delimiter;
if (map[key] == null)
{
map[key] = id;
var node:XML = <child id = {id} label = {itemArray[j]}/>;
if (j == 0)
data.appendChild(node);
else
data..child.(@id == map[prevkey]).appendChild(node);
id++;
}
}
}
}
}