怎么用XPath根据节点属性值获取所需节点
本帖最后由 rayborn1105 于 2012-04-14 01:54:23 编辑 大家好,最近刚接触XPath,学校有个实验室在Acrobat中用JS操纵XML数据,里面用到了XPath,但是我用了很多方法都取不到数据,所以希望大家帮我看看怎么才能取到。XML文档如下:(因为用了Acrobat写入XML后,自动加入了下面标注为红字的代码)
<?xml version="1.0" encoding="UTF-8"?>
<xfa:data xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/">
<mapData>
<busline>
<id>4</id>
<name>K222</name>
<stationList>
<station>
<name>FirstStation</name>
<stationAnnotName>station</stationAnnotName>
<cordX>-309</cordX>
</station>
<station>
<name>222first</name>
<stationAnnotName>station3</stationAnnotName>
<cordX>-315</cordX>
</station>
</stationList>
</busline>
<busline>
<id>5</id>
<name>K333</name>
<stationList>
<station>
<name>ss</name>
<stationAnnotName>station</stationAnnotName>
<cordX>-309</cordX>
</station>
<station>
<name>Target</name>
<stationAnnotName>station3</stationAnnotName>
<cordX>-315</cordX>
</station>
</stationList>
</busline>
</mapData>
</xfa:data>
我现在要找的是station节点中name为Target的这个station,并得到这个station的cordX中的值,另外需要获取包含这个station的name属性为target的busline中的name属性值。
即获取黄色标注的2个属性值。
还望各位高手帮我看看,怎么写XPath语句可以完成以上所求。
谢谢大家了!!!
[解决办法]
以下是javascript示例,xpath表达式在其它语言中也是一样的。可以直接拿过去用
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>无标题文档</title>
<script type="text/javascript" src="http://www.chhblog.com/scripts/zxml.src.js"></script>
</head>
<body>
<textarea id='txt'>
<?xml version="1.0" encoding="UTF-8"?>
<xfa:data xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/">
<mapData>
<busline>
<id>4</id>
<name>K222</name>
<stationList>
<station>
<name>FirstStation</name>
<stationAnnotName>station</stationAnnotName>
<cordX>-309</cordX>
</station>
<station>
<name>222first</name>
<stationAnnotName>station3</stationAnnotName>
<cordX>-315</cordX>
</station>
</stationList>
</busline>
<busline>
<id>5</id>
<name>K333</name>
<stationList>
<station>
<name>ss</name>
<stationAnnotName>station</stationAnnotName>
<cordX>-309</cordX>
</station>
<station>
<name>Target</name>
<stationAnnotName>station3</stationAnnotName>
<cordX>-315</cordX>
</station>
</stationList>
</busline>
</mapData>
</xfa:data>
</textarea>
<script type="text/javascript">
var doc = zXmlDom.createDocument();
doc.loadXML(document.getElementById('txt').value);
var name1 = zXPath.selectSingleNode(doc,'//mapData/busline/stationList/station[name="Target"]/cordX/text()');
var name2 = zXPath.selectSingleNode(doc,'//mapData/busline[stationList/station/name[text()="Target"]]/name/text()');
alert(name1.nodeValue)
alert(name2.nodeValue)
</script>
</body>
</html>