KK99
KK99

Reputation: 1989

Configuring XPath and use LINQ

i have a scenario where i need to check for the node count in a XML file. Since the XPath may vary for different scenarios, i would like to configure this in a xml / text file

I checked at XQuery but I hardly find any implementation in C#.

Since LINQ also does the similar thing, i am thinking of using it.

Ex. XML:

<ROOT><NODE1><TXT>ABC</TXT></NODE1><NODE1><TXT>DEF</TXT></NODE1></ROOT>

I would like to configure my condition like this (in a text file):

/ROOT/NODE1/TXT [COUNT=2]

there will n-number of xpath like this

How easily can I use LINQ, Check for XPATH and get the count?

Thanks in advance

Cheers, Karthik

Upvotes: 0

Views: 262

Answers (2)

Rozuur
Rozuur

Reputation: 4165

Check the reference System.Xml.Xpath which allows you to use xpath to work with Xml data.

XDocument doc = XDocument.Load(filePath);
var xPath = @"/ROOT/NODE1/TXT";
int count = doc.XPathSelectElements(xPath).Count();

Upvotes: 3

Saeed Amiri
Saeed Amiri

Reputation: 22555

XDocument doc = XDocument.Load(xmlFilePath);
int count = doc.Descendants("TXT").Count();

In this case you can do:

        XDocument doc = XDocument.Load(filePath);
        var xPath = @"/ROOT/NODE1/TXT";
        int count = doc.Descendants(xPath.Substring(xPath.LastIndexOf("//") + 1)).Count();

but it's not general case, whould you explain more details about your condition to force using XPath strings?

Upvotes: 0

Related Questions