0

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#

3
  • 4
    Your XML seems malformed for me: Id=1 => Id="1" Commented Jan 25, 2013 at 10:53
  • Also, you'd said what you tried - but not what the result was. (And do you have to use XPath? I'd personally use LINQ to XML...) Commented Jan 25, 2013 at 10:56
  • 1
    And your second and third Title havea wrong end tag. <Title/> Commented Jan 25, 2013 at 10:56

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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";

1 Comment

lower-case() would be better, if .NET supported XPath 2.0, which it does not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.