Xml 使用xpath选择具有一组多个属性/值的元素
我有一个XML文档,需要将特定的数据片段剥离出来 xml文档的结构如下所示:-Xml 使用xpath选择具有一组多个属性/值的元素,xml,xslt,xpath,Xml,Xslt,Xpath,我有一个XML文档,需要将特定的数据片段剥离出来 xml文档的结构如下所示:- <a> <b select='yes please'> <c d='text1' e='text11'/> <c d='text2' e='text12'/> <c d='text3' e='text13'/> <c d='text4' e='text14'/> <
<a>
<b select='yes please'>
<c d='text1' e='text11'/>
<c d='text2' e='text12'/>
<c d='text3' e='text13'/>
<c d='text4' e='text14'/>
<c d='text5' e='text15'/>
</b>
</a>
<a>
<b select='no thanks'>
<c d='text1' e='text21'/>
<c d='text3' e='text23'/>
<c d='text5' e='text25'/>
</b>
</a>
<a>
<b select='yes please'>
<c d='text1' e='text31'/>
<c d='text2' e='text32'/>
<c d='text3' e='text33'/>
<c d='text4' e='text34'/>
<c d='text5' e='text35'/>
</b>
</a>
<a>
<b select='no thanks'>
<c d='text4' e='text41'/>
<c d='text3' e='text43'/>
<c d='text5' e='text45'/>
</b>
</a>
我只需要选择那些具有d属性='text1'和
d attribute='text4',一旦我识别了这些子文档,我想用d属性值'text5'获取e属性的值
希望这是清楚的
干杯
DD您可以使用以下XPath:
//a[b/c/@d = 'text1' and b/c/@d = 'text4']/b/c[@d = 'text5']/@e
它将选择第一个和第三个a/b的e='text15'
和e='text35'
XSLT:
您可以使用单个模板匹配所需的组,然后获得所需属性的值:
<xsl:template match="/*/a/b[c[@d='text1'] and c[@d='text4']]">
<xsl:value-of select="c[@d='text5']/@e"/>
</xsl:template>
假设:
<root>
<a>
<b select='yes please'>
<c d='text1' e='text11'/>
<c d='text2' e='text12'/>
<c d='text3' e='text13'/>
<c d='text4' e='text14'/>
<c d='text5' e='text15'/>
</b>
</a>
<a>
<b select='no thanks'>
<c d='text1' e='text21'/>
<c d='text3' e='text23'/>
<c d='text5' e='text25'/>
</b>
</a>
<a>
<b select='yes please'>
<c d='text1' e='text31'/>
<c d='text2' e='text32'/>
<c d='text3' e='text33'/>
<c d='text4' e='text34'/>
<c d='text5' e='text35'/>
</b>
</a>
<a>
<b select='no thanks'>
<c d='text4' e='text41'/>
<c d='text3' e='text43'/>
<c d='text5' e='text45'/>
</b>
</a>
</root>
输出将是text15
和text35
我只需要选择那些具有d属性='text1'和d属性='text4'的/a/b元素组,一旦我识别了这些子文档,我就想获得具有d属性值'text5'的e属性的值
希望这是清楚的
是的,很明显,到XPath的转换几乎是机械的
(: those /a/b element groups :) a/b
(: that have d attribute = 'text1' :) [c/@d='text1']
(: and d attribute = 'text4' :) [c/@d='text4']
(: and .. i want to get the value of the e attributes
with d attribute value 'text5' :) / c[@d='text5'] / @e
使用这个XPath表达式:
/*/a/b[c/@d='text1' and c/@d='text4']
/c[@d='text5']
/@e
+xpath/xslt星期天问题1:)哦,现在是星期六…@empo,在某些区域已经是星期天了:-)好问题,+1。请参阅我的答案,以获得一个XPath表达式,该表达式精确地选择了所需的属性。@user423199,您可以标记为answer或upvote适当的answer。我不是downvoter。但我可以认为这是一个微妙的否决票,指的是你对c
的祖先a
进行谓词,而(如其他答案所示)它对c
的直系父b
进行更自然的谓词。你也失去了可读性。@empo,但如果它如此“微妙”,downvoter可以解释他的观点。我不喜欢沉默@downvoctors。谢谢你不厌其烦地关注我的问题,它让我发疯了!谢谢你花时间在it@user不客气。这里的“棘手”部分是匹配一个元素,对于该元素,我们至少有两个具有不同属性值的相同子元素的实例。为了清楚起见,您需要使用和嵌套的predicate.FYI—对于那些不熟悉的人,(:)
是XPath 2.0注释。如果您使用的是XPath 1.0,请删除注释并只使用XPath语句,即a/b[c/@d='text1'][c/@d='text4']/c[@d='text5']/@e
/*/a/b[c/@d='text1' and c/@d='text4']
/c[@d='text5']
/@e