tags:

views:

411

answers:

2

This question is close, but it's looking for the ordinal position. I'm looking for the actual index position in a given source string.

Better Explanation:

I have the following string

"<a>
    <b>zyx</b>
    <b>wvu</b>
    <b>tsr</b>
    <b>qpo</b>
</a>"

I'm loading that string into a .NET XmlDocument object. Carriage Returns and Line Fees may be a factor here.

Dim xmlSearchText As New XmlDocument()
xmlSearchText.LoadXml(SearchTextBox.Text)

Dim selectedNode As XmlNode = xmlSearchText.SelectSingleNode(txtSearch.Text)

The following XPath Statement could be used to find the 3rd node:

a/b[.='tsr']

However, I need it to return a string index of 23 rather than the ordinal position of 3.

Possible? Not Possible?

A: 

Does this give you what you want?

selectedNodenode = xmlSearchText.SelectSingleNode("a/b[.='tsr']");
selectedNode.ParentNode.OuterXml.IndexOf(selectedNode.OuterXml)

Won't give you the index from the root, but it'll give you the index from the parent node.

Chris Persichetti
It gets me pretty darn close. I'm currently using (as of the time of this comment) SearchTextBox.Text.IndexOf(selectedNode.OuterXml)
Joshua Hayworth
A: 

Using XPathDocument instead of XmlDocument will let you 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 need the character index from the string, you can deduce it by counting newlines int the string and adding the column.

Coincoin