XPath expression to go to next <relatedfile> field
I am trying to read a file that is set up as follows:
<file>
<name>My name</name>
<size>My size</size>
<relatedfiles>
<relatedfile>My related file 1</relatedfile>
<relatedfile>My related file 2</relatedfile>
<relatedfile>My related file 3</relatedfile>
</relatedfiles>
</file>
To get the name/size fields, I am using the XPath expression
"file/name"
and
"/size"
which has worked so f开发者_开发知识库ar.
Now, I want to read the related files, one related file at a time. I have looked into getting the first as
/relatedfiles/relatedfile
which gets me to the first related file, but I don't know how to get to the next single one (I have seen examples including following-sibling, but the tutorials state that it returns ALL siblings, and I only want to work one at a time)...
Thanks.
/relatedfiles/relatedfile[<index>] will get you specific nodes. Note though that XPath indexes from 1.
EDIT
Ok I should have caught this and I'm sorry that I posted what I had done above.
The correct path should have been //relatedfiles/relatedfile[<index>]
That says, regardless of context, look through all nodes and locate anything that starts with relatedfiles find sub nodes related file, get me the indexed element.
You could easily have written this as //relatedfiles[<index>] as well
If you are using XQuery (of which XPath is a subset), the EXPath file module allows you to iterate with a for clause and perform operations on each individual file, something like:
for $file in doc("file.xml")//relatedfile
where f:exists($file)
return f:read-text($file)
This returns a sequence of strings, each of which contains the contents of a file among those which exist.
If you have the XPath someExpr
that selects a wanted element and want to select the next sibling such element, use:
someExpr/following-sibling::myElementName[1]
//relatedfiles/relatedfile will return all three. you can iterate over or you can select by filtering for the specific index u are interested in: //relatedfiles/relatedfile[n]
to loop, you can do something like
<xsl:for-each select="//relatedfiles/relatedfile">
<xsl:value-of select="."/>
</xsl:for-each>
精彩评论