How can I find the string position (index) from an XPath statement?
This question is close, but it is looking for an ordinal position. I am looking for the actual index position in a given source string.
Better explanation:
I have the following line
"<a>
<b>zyx</b>
<b>wvu</b>
<b>tsr</b>
<b>qpo</b>
</a>"
I am loading this string into a .NET XmlDocument object. Carriage return and cap can be a factor here.
Dim xmlSearchText As New XmlDocument()
xmlSearchText.LoadXml(SearchTextBox.Text)
Dim selectedNode As XmlNode = xmlSearchText.SelectSingleNode(txtSearch.Text)
The following XPath expression can be used to find the third node:
a/b[.='tsr']
However, I need to return line index 23, not ordinal position 3.
Possible? Impossible?
0
a source to share
2 answers
Using XPathDocument instead of XmlDocument will allow you to access the IXmlLineInfo interface with line number and column position.
XPathDocument document = new XPathDocument("file.xml");
XPathNavigator navigator = document.CreateNavigator();
XPathNavigator node = navigator.Select("a/b[.='tsr']");
IXmlLineInfo info = ((IXmlLineInfo)node);
Console.WriteLine("Found at ({0},{1})",info.LineNumber,info.LinePosition);
If you really want the index of the character from the string, you can output it by counting the newlines and adding a column.
0
a source to share