aharon
aharon

Reputation: 7643

Search in whole xml in C#

I whant to create a function that return True if a specified string is in the xml document. The problem is that i need to search in the whole document and not a specifide element, and the xml can contain severals levels... how can i do that?

Upvotes: 0

Views: 619

Answers (2)

Dan McClain
Dan McClain

Reputation: 11920

Treat the contents of the XML as a string, and just search the content string for the one you are looking for.

public bool FileContainsString(string filePath, string searchString)
{
    string fileContents;
    using(FileStream file = new FileStream(filePath, FileMode.Open))
    using(StreamReader reader = new StreamReader(reader))
    {
        fileContents = reader.ReadToEnd();
    }

    return fileContents.Contains(searchString);
}

This code was not tested

If you want a case-insensitive search for the string, replace

    return fileContents.Contains(searchString);

with

    return fileContents.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) > -1;

Upvotes: 7

Felice Pollano
Felice Pollano

Reputation: 33252

XmlDocument doc;
bool contains = doc.InnerXml.IndexOf("Your text") != -1 

should do the trick, but it will find the text even if it is contained in a tag, if you want just to check for plain text use:

XmlDocument doc;
    bool contains = doc.InnerText.IndexOf("Your text") != -1 

Upvotes: 0

Related Questions