How to find out what is the "number" of xml element I specify
Let's say I have xml structure like this
<root>
<element>some content</element>
<element>some content 2</element>
<element>some content 3</element>
<element>some content 4</element>
<element>some content 5</element>
<element>some content 6</element>
<element>some content 7</element>
<element>some content 8</element>
<element>some content 9</element>
<element>some content 10</element>
</root>
I have plenty of tags in the root, let's say 1000, and each of them contains different data of 开发者_JAVA百科course (not unique), my problem is ... what is the fastest way how to find out the number of the element, for instance if I work with element "some content 8" I want to get number 8, I know that xpath is probably the right tool for that but it seems to me very slow (I want to do that like in few seconds, because I use it very often)
Maybe some "vim" way how to do this?
Thank you
You could count all the times a substitute of <element>
would occur from the first up to the current line:
:0,.s/<element>//gn
Note that the n
flag prevents the substitute from actually occuring.
This will obviously not work for all conceivable types of XML but might fit your data.
To pull out the number from the current line you can use the following ex command in vim:
:echo substitute(getline('.'), '.*\(\d\+\).*', '\1', '')
A pure XPath solution:
count(/*/element[. = 'some content 8']/preceding-sibling::*) +1
To verify this easily you can use a tool like the XPath Visualizer, or the following XSLT-based verification:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/">
<xsl:value-of select=
"count(/*/element[. = 'some content 8']/preceding-sibling::*) +1"/>
</xsl:template>
</xsl:stylesheet>
When this transformation is performed on the provided XML document:
<root>
<element>some content</element>
<element>some content 2</element>
<element>some content 3</element>
<element>some content 4</element>
<element>some content 5</element>
<element>some content 6</element>
<element>some content 7</element>
<element>some content 8</element>
<element>some content 9</element>
<element>some content 10</element>
</root>
the result from evaluating the XPath expression is output, and it is correct:
8
精彩评论