如何从XML获取XPath?

时间:2012-05-09 07:10:01

标签: xpath

我有一个xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<response>
    <rows>
        <column account="1" name="balibid" seq="1">1</column>
        <column account="1" name="genre" seq="1">Kids</column>
        <column account="1" name="ph" seq="1">3</column>
        <column account="1" name="ph" seq="1">4</column>
        <column account="1" name="ph" seq="1">5</column>
        <column account="1" name="ph" seq="1">6</column>
        <column account="1" name="pl6" seq="1">6</column>
 </rows>
</response>

我需要列名称=流派的XPath。我该怎么用?

3 个答案:

答案 0 :(得分:3)

在XPATH查询中使用//导致不必要的(并且可能是昂贵的)评估,这是我开始的方式(因为它很容易),但我现在正在努力戒掉这个习惯。

鉴于你提供了一个很好的,形式良好的样本。以下是两个示例XPATH查询:

/response/rows/column[@name="genre"]

并且

rows/column[@name="genre"]

答案 1 :(得分:0)

试试这个:

//column[@name='genre']

答案 2 :(得分:0)

使用(针对特定提供的XML文档):

/*/*/*[@name = 'genre']

基于XSLT的验证:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="/">
     <xsl:copy-of select="/*/*/*[@name = 'genre']"/>
 </xsl:template>
</xsl:stylesheet>

在提供的XML文档上应用此转换时:

<response>
    <rows>
        <column account="1" name="balibid" seq="1">1</column>
        <column account="1" name="genre" seq="1">Kids</column>
        <column account="1" name="ph" seq="1">3</column>
        <column account="1" name="ph" seq="1">4</column>
        <column account="1" name="ph" seq="1">5</column>
        <column account="1" name="ph" seq="1">6</column>
        <column account="1" name="pl6" seq="1">6</column>
 </rows>
</response>

评估XPath表达式并将所选节点复制到输出中:

<column account="1" name="genre" seq="1">Kids</column>