开发者

How to retrieve the particular X th position of node using xpath?

This is my Xml Document.

开发者_StackOverflow社区
<w:document>
<w:body>
   <w:p>para1</w:p>
   <w:p>para2</w:p>
   <w:p>para3</w:p>
   <w:p>para4</w:p>
   <w:p>para5</w:p>
   <w:p>para6</w:p>
   <w:p>para7</w:p> 
   <w:p>para8</w:p>
   <w:p>para9</w:p>
   <w:p>para10</w:p>
</w:body>
</w:document>

Now, i want to retrieve the text of 7th .ie,Para7.

How do i get it?


You can index into an XPath expression using [] brackets. For example, you might use //w:p[7] to access the 7th element.

Note that XPath indexing is 1-based indexing not 0-based indexing.


Use:

/*/*/*[7]/text()

If you have registered the namespaces correctly with your XPath engine's API, you can use:

/w:document/w:body/w:p[7]/text()

Note:

Be aware that there are problems using the [] operator together with the // pseudo-operator: in this specific simple case the expression

//w:p[7] 

selects the wanted element, however in general it selects every w:p element that is the 7th (in document order) w:p child of its parent.

So, when evaluated against this document:

<w:document xmlns:w="w:w">
    <w:body>
     <a>
        <w:p>para1</w:p>
        <w:p>para2</w:p>
        <w:p>para3</w:p>
   </a> 
   <b>
        <w:p>para4</w:p>
        <w:p>para5</w:p>
        <w:p>para6</w:p>
        <w:p>para7</w:p>
        <w:p>para8</w:p>
        <w:p>para9</w:p>
        </b>
        <w:p>para10</w:p>
    </w:body>
</w:document>

the expression //w:p[7] selects nothing.

However, when evaluated against this document:

<w:document xmlns:w="w:w">
    <w:body>
     <a>
        <w:p>para1</w:p>
        <w:p>para2</w:p>
        <w:p>para3</w:p>
        <w:p>para4</w:p>
        <w:p>para5</w:p>
        <w:p>para6</w:p>
        <w:p>para7</w:p>
        <w:p>para8</w:p>
   </a>
   <b>
        <w:p>para9</w:p>
        <w:p>para10</w:p>
        <w:p>para11</w:p>
        <w:p>para12</w:p>
        <w:p>para13</w:p>
        <w:p>para14</w:p>
        <w:p>para15</w:p>
    </b>
 </w:body>
</w:document>

the same expression selects:

<w:p xmlns:w="w:w">para7</w:p>
<w:p xmlns:w="w:w">para15</w:p>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜