tags:

views:

56

answers:

2

I am trying to search an xml element from the root element of the file on the basis of inner text. i have tried this but didnt work:

rootElRecDocXml.SelectSingleNode("/ArrayOfRecentFiles[name='"+mFilePath+"']");

I know the old school way to traverse all file elemen by element but i dont want to do that.

Please note that: my root element name is ArrayOfRecentFiles and my child elements names are RecentFile

+1  A: 

You need to use "text()" to check against the inner text of an element as below.

rootElRecDocXml.SelectSingleNode("/ArrayOfRecentFiles[text()='"+mFilePath+"']");
Lee Hesselden
it is returning null
jaminator
Try this then didn't realise you had an additional child node level rootElRecDocXml.SelectSingleNode("/ArrayOfRecentFiles/RecentFile[text()='"+mFilePath+"']");
Lee Hesselden
+1  A: 

We'd need to see the xml; @Lee gives the correct approach here, so something like:

var el = rootElRecDocXml.SelectSingleNode(
          "/ArrayOfRecentFiles/RecentFile[text()='"+mFilePath+"']");

(taking your edit/reply into account)

However! There are lots of gotchas:

  • the query will be case-sensitive
  • white-space will be significant (so <foo>abc</foo> is different to <foo> abc[newline]</foo> etc - ditto carriage return)
  • xml namespaces are significant, so you may need .SelectSingleNode("/alias:ArrayOfRecentFiles[text()='"+mFilePath+"']", nsmgr);, where nsmgr is the namespace-manager

To give a complete example, that matches your comment:

XmlDocument rootElRecDocXml = new XmlDocument();
rootElRecDocXml.LoadXml(@"<ArrayOfRecentFiles> <RecentFile>C:\asd\1\Examples\8389.atc</RecentFile> <RecentFile>C:\asd\1\Examples\8385.atc</RecentFile>   </ArrayOfRecentFiles>");
string mFilePath = @"C:\asd\1\Examples\8385.atc";
var el = rootElRecDocXml.SelectSingleNode(
    "/ArrayOfRecentFiles/RecentFile[text()='" + mFilePath + "']");

Here, el is not null after the SelectSingleNode call. It finds the node.

Marc Gravell
the above is my xml
jaminator
this is my xml:<ArrayOfRecentFiles> <RecentFile>C:\asd\1\Examples\8389.atc</RecentFile> <RecentFile>C:\asd\1\Examples\8385.atc</RecentFile> </ArrayOfRecentFiles>
jaminator
@jaminator - see update
Marc Gravell