parsing table in XPATH
<TR>
<TD&开发者_JAVA技巧gt;Field 1</TD>
<TD colSpan=2>Field 2</TD>
<TD>Field 3</TD>
</TR>
<TR>
<TD>Value for Field1</TD>
<TD colSpan=2>Value for Field2</TD>
<TD>Value for Field3</TD>
<TR></TR>
</TR>
How can i map the Field with its value? I am using XPATH to parse my html file.
And the main problem is the number of fields change in each and every input..But as you know the layout will be same....
This will select you field names:
//table/tr[position() mod 2 = 0]/td/text()
This will select you field values:
//table/tr[position() mod 2 = 1]/td/text()
This XPath expression:
/*/*[2]/TD
[position()
=
count(/*/*[1]
/TD[.=$pName]/preceding-sibling::TD
) +1
]
selects the TD
with "value" corresponding to the "name" specified in the variable pName
Thus, if you substitute $pName
in the above expression with 'Field 2'
,the following will be selected:
<TD colSpan="2">Value for Field2</TD>
Note: This XPath expression selects the correct node even in the case when the two rows have different number of TD
s.
To select only the text child node of the TD
, append /text()
to the expression.
To get just the string value, use:
string(/*/*[2]/TD
[position()
=
count(/*/*[1]
/TD[.=$pName]/preceding-sibling::TD
) +1
]
)
Here is a short XSLT transformation proving that the wanted value is retrieved:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:param name="pName" select="'Field 2'"/>
<xsl:template match="/">
<xsl:value-of select=
"/*/*[2]/TD
[position()
=
count(/*/*[1]
/TD[.=$pName]/preceding-sibling::TD
) +1
]
"/>
</xsl:template>
</xsl:stylesheet>
when this transformation is applied against the provided XML document (fixed to be made well-formed):
<TABLE>
<TR>
<TD>Field 1</TD>
<TD colSpan="2">Field 2</TD>
<TD>Field 3</TD>
</TR>
<TR>
<TD>Value for Field1</TD>
<TD colSpan="2">Value for Field2</TD>
<TD>Value for Field3</TD>
<TR></TR></TR>
</TABLE>
the wanted result is produced:
Value for Field2
With this input:
<TABLE>
<TR>
<TD>Field 1</TD>
<TD colSpan="2">Field 2</TD>
<TD>Field 3</TD>
</TR>
<TR>
<TD>Value for Field1</TD>
<TD colSpan="2">Value for Field2</TD>
<TD>Value for Field3</TD>
</TR>
</TABLE>
This XPath expression:
/TABLE/TR/TD[.='Field 3']/following::TD[count(../TD)]
It selects this element:
<TD>Value for Field3</TD>
Note: This assumes a "regular" table.
精彩评论