Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find an element in xml by its inner text

Tags:

c#

.net

xml

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 element by element but i dont want to do that.

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

like image 651
PUG Avatar asked Jul 12 '10 08:07

PUG


1 Answers

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.

like image 179
Marc Gravell Avatar answered Oct 16 '22 15:10

Marc Gravell