如何使用XPath获取XML中所有指定属性的字符串值?
name Attribute Values Separated by Space The issue with string(//model:testFile/@name) is that in XPath, passing a node set to the string() function only returns the string value of the first node in the set. To get all values joined by spaces, here's how to fix it depending on your XPath version:
XPath 2.0 and Later (Recommended)
Use the string-join() function—this purpose-built tool takes a sequence of strings and a separator, then concatenates them cleanly:
string-join(//model:testFile/@name, ' ')
This will return exactly what you need: $test1$ $test2$, and it works seamlessly for any number of model:testFile elements, not just two.
XPath 1.0 (Legacy)
XPath 1.0 lacks a built-in string-join function, so you have a couple of practical workarounds:
Option 1: Explicit Concatenation (Fixed Number of Elements)
If you know exactly how many model:testFile elements exist, use concat() to combine their values directly:
concat(//model:testFile[1]/@name, ' ', //model:testFile[2]/@name)
This works for your specific example but isn't scalable if the number of elements varies.
Option 2: XSLT Loop (Dynamic Element Count)
If you're using XPath within XSLT 1.0, loop through each element and output the value with a space (avoiding a trailing space):
<xsl:for-each select="//model:testFile"> <xsl:value-of select="@name"/> <xsl:if test="position() != last()"> </xsl:if> </xsl:for-each>
Critical Note: Namespace Binding
Ensure the model: prefix is properly bound to the correct XML namespace in your XPath processing context. Without this declaration, the query won't match any elements, even if the prefix looks correct in your XML.
内容的提问来源于stack exchange,提问作者www

