开发者

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 var开发者_如何转开发y 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


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();


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜