如何使用XPath分别捕获XML所有属性与文本,及在XSLT中单独获取指定属性值和文本值
Correct XPath & XSLT to Capture XML Attributes and Text
Let's break down how to fix your XPath expressions and achieve what you need with your XML structure.
Issues with Your Current Code
First, let's address why your existing variables aren't working as expected:
- For
vQueryAttribute: The syntax@[localname()='name']is invalid. To select thenameattribute, use@name(or@*[localname()='name']if you need to avoid namespace conflicts, though it's unnecessary here). Also, wrapping the expression instring()will only return the first attribute value, not all of them. - For
QueryText:$vQueryParam/request/args/arg[@name]selects all<arg>elements with anameattribute, butstring()will only return the text of the first matching element.
1. Retrieve All Attribute Values and Text Nodes
If you want to get every name attribute and its corresponding text value:
- All
nameattributes: Use this XPath to select all attributes:$vQueryParam/request/args/arg/@name - All text values: Use this XPath to select all text nodes inside
<arg>elements:$vQueryParam/request/args/arg/text()
2. Target Specific Attribute Values and Their Text
To access individual entries like CacheVM, junk, or bcd:
- Get text for a specific attribute: For example, to fetch the text associated with
CacheVM:$vQueryParam/request/args/arg[@name='CacheVM']/text() - Get attribute value by position: If you know the index of the
<arg>element, use:<!-- First attribute value --> $vQueryParam/request/args/arg[1]/@name <!-- First text value --> $vQueryParam/request/args/arg[1]/text()
3. Example XSLT to Loop Through All Entries
If you want to process each <arg> element and output its attribute and text, use an <xsl:for-each> loop:
<xsl:for-each select="$vQueryParam/request/args/arg"> <entry> <attribute-name><xsl:value-of select="@name"/></attribute-name> <text-value><xsl:value-of select="text()"/></text-value> </entry> </xsl:for-each>
4. Correct Variable Definitions
To store specific values in variables for later use:
<!-- Variable for CacheVM's text value --> <xsl:variable name="cacheVmText" select="$vQueryParam/request/args/arg[@name='CacheVM']/text()"/> <!-- Variable for the second arg's attribute name --> <xsl:variable name="secondArgName" select="$vQueryParam/request/args/arg[2]/@name"/>
This gives you full control over accessing both attributes and text values in your XML structure.
内容的提问来源于stack exchange,提问作者Karthik Grandhi
相关产品推荐
相关产品推荐

