2015-11-10 169 views
0

是否可以使用substring-before和substring-after作为选择器?如果不是,你会怎么做?substring-after和substring-before使用元素而不是字符串

如果我有这样的片段,例如,

<root> 
    <element>This is an example. Some text here | and some text there</element> 
</root> 

我可以用串 - 前或子,后与管道|获得左侧或右侧的文本

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
xmlns:xs="http://www.w3.org/2001/XMLSchema" 
exclude-result-prefixes="xs" 
version="2.0"> 

<xsl:template match="root">   
    <element><xsl:value-of select="substring-before(element, '|')"/></element> 
</xsl:template> 
</xsl:stylesheet> 

得到

<?xml version="1.0" encoding="UTF-8"?> 
<element1>This is an example. Some text here </element1> 

但我怎么能做到这一点与将文本,如LB或ALT的元素?

<?xml version="1.0" encoding="UTF-8"?> 
<root> 
    <element>This is an example. Some text here <alt type="divider"/> and some text there</element> 
</root> 

我在想兄弟姐妹的事情,但我不想返回一个元素,但字符串。所以我无法真正包围它。

预先感谢您!

+0

你不能在选择器轴上使用'text()'吗? –

+0

“*我怎么能用一个元素分割文本*”一个元素永远不会分割文本“。你展示的是三个独立的兄弟节点:一个文本节点,一个元素节点和另一个文本节点。 –

+0

你已经以错误的方式经典地表述了这个问题:你不是问“我怎么能达到X”,而是问“我可以用双头锤子吗?”;这让我们去研究这个帖子,以发现你想要的结果,并告诉你,双头锤子不是要走的路。事实上,你说这个问题的方式表明你正在将XML文档看作是带有交织标记的内容串,而不是节点树。你需要改变这种想法! –

回答

0

路径/root/element/text()[1]会给你的文本节点alt元素之前,路径/root/element/text()[2]文本节点alt元素之后,这是假定你知道有这样的元素,你必须通过一个元素分开的两个文本节点。 value-of总是输出一个节点的字符串值,你永远不会输出一个节点本身value-of

0

是的,这个XPath表达式

/root/element/text()[not(preceding-sibling::alt)] 

alt之前选择文本

and some text there 

和他的XPath表达式,

/root/element/text()[not(following-sibling::alt)] 

后选择文本 the alt

and some text there 
相关问题