我正在使用 jquery 解析 xml。我附上了一张图片,显示了我想要解析的那种 xml。如您所见,它有几个标签,但我需要按照图像中出现的顺序解析以下内容。
ROUTE
LENGTH time dist
WALK time dist
LINE code
STOP //<--- this stop means all stops in this line tag
NAME val //<--- val of every stop inside line tag
STOP //<--- this stop means all stops in this line tag
NAME val //<--- val of every stop inside line tag
STOP //<--- this stop means all stops in this line tag
NAME val //<--- val of every stop inside line tag
LINE code
STOP //<--- this stop means all stops in this line tag
NAME val //<--- val of every stop inside line tag
STOP //<--- this stop means all stops in this line tag
NAME val //<--- val of every stop inside line tag
STOP //<--- this stop means all stops in this line tag
NAME val //<--- val of every stop inside line tag
WALK time dist
注意:可能有 1、2 或多于 2 个 LINES 标签。
我当前的代码确实显示了数据,但只有一个,即第一行,并且只有该行内的第一个 STOP。那么如何解析这个 xml 以便可以在 XML 中显示它呢?
这是我的代码
parseXMLForRoute = function (xmlObject) {
var xmlObj = $(xmlObject).find('ROUTE');
xmlObj.each(function () {
var el = $(this),
startTime = el.find('WALK').find('LENGTH').attr('time'),
distance = el.find('WALK').find('LENGTH').attr('dist'),
routeTime = el.find('LENGTH').attr('time'),
routeDist = el.find('LENGTH').attr('dist'),
busNumber = el.find('LINE').attr('code').slice(1, 4),
busStops = el.find('LINE').find('STOP').find('NAME').attr('val');
container.append(createDOMElement('h4', '', '', 'Departure'))
.append(createDOMElement('p', '', '', from))
.append(createDOMElement('p', '', '', "Route Time: " + routeTime))
.append(createDOMElement('p', '', '', "Route Dist: " + routeDist))
.append(createDOMElement('section', '', '', 'WALK PIC'))
.append(createDOMElement('p', '', '', "Walk Time: " + startTime))
.append(createDOMElement('p', '', '', "Walk Dist: " + distance))
.append(createDOMElement('p', '', '', 'BUS PIC'))
.append(createDOMElement('p', '', '', "Bus Number: " + parseLineNumbers(xmlObj)))
.append(createDOMElement('p', '', '', "Bus Stops: " + busStops));
//console.log($(this).find('WALK'));
});
console.log($(xmlObject));
},
parseLineNumbers = function (xmlObject) {
console.log('len: ' + $(xmlObject).find('LINE').length);
$(xmlObject).find('LINE').each(function () {
console.log($(this).attr('code').slice(1, 4));
});
//console.log($(xmlObject).find('LINE').attr('code').slice(1, 4));
},
createDOMElement = function (tagName, classs, id, data) {
return '<' + tagName + ' class="' + classs + '" id="' + id + '">' + data + '</' + tagName + '>';
}
这是xml
更新
我想要输出类似于下面的内容
Starting street address
WALK this amount of distance(e.g. 1 meter) for some time(e.g. 1 min)
STOP name // after walking then user reached to this stop
code // code attribute inside LINE tag which is a bus number
then display the name and times of all stops in this LINE
code // code attribute inside SECOND LINE
then display all the stops name and times in this second LINE
then walk for some distance(e.g. 1 meter) and some time(e.g. 1 min)
Destination address