Gourav Goyal
Gourav Goyal

Reputation: 37

How To Retrieve specific node using Xpath c#

I have an xml file

<BookLib>
  <Book Id="1">
    <Title>Title1</Title>
    <Author>Author1</Author>
    <Publisher>Publisher1</Publisher>
    <Subject />
  </Book>
  <Book Id="2">
    <Title>Title2</Title>
    <Author>Author2</Author>
    <Publisher>Publisher2</Publisher>
    <Subject />
  </Book>
  <Book Id="3">
    <Title>Title3</Title>
    <Author>Author3</Author>
    <Publisher>Author3</Publisher>
    <Subject />
  </Book>
</BookLib>

I want to select book id. I tried using this

@"/BookLib/Book/Title[contains(translate(text(),'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz'),'" + searchText + "')]/@Id";

in XPathExpression

how can i retrieve 'id' using xpath in c#

Upvotes: 0

Views: 241

Answers (2)

&#201;douard Lopez
&#201;douard Lopez

Reputation: 43401

First you can use fn:lower-case() which is better than fn:translate as it use Unicode mapping to change the case. So it will work with accent like É->é, À->à, etc.

Then you can simplify by using XPath axes.

So, to get the @Id, you can use the following XPath (adapt to C#) :

@"//Book/Title[contains(lower-case(./text()),'" + searchText.ToLower() + "' )]/@Id";

Upvotes: 0

JLRishe
JLRishe

Reputation: 101680

Since @Id is below Book, not Id, you have to move back up to get it:

@"/BookLib/Book/Title[contains(translate(.,'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'),'" 
      + searchText.ToLower() + "')]/../@Id";

or do the comparison without moving down to Title in the first place:

@"/BookLib/Book[contains(translate(Title,'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'),'" 
      + searchText.ToLower() + "')]/@Id";

I personally prefer the latter because it seems a bit cleaner.

Upvotes: 1

Related Questions