0

I'm trying to get an attribute from the XML but I'm getting an error:

Expression must evaluate to a node-test

I'm new to XPath.

XML file example:

<Message>
   <Head>
      <Sender Identifier="id" ref=""/>
   </Head>
</Message>

Code:

XPathDocument xDoc = new XPathDocument("documentName.xml");
XPathNavigator nav = xDoc.CreateNavigator();
XPathNodeIterator xpathNode = nav.Select("/Message/Head/Sender/[@Identifier]");
//This is where I get the error.

And I'm also not sure how to display the attribute value.

2
  • I did but ass it but its not showing up, im nto sur ewhy Commented Nov 29, 2012 at 8:47
  • 1
    Welcome to StackOverflow: if you post code, XML or data samples, please highlight those lines in the text editor and click on the "code samples" button ( { } ) on the editor toolbar to nicely format and syntax highlight it! Commented Nov 29, 2012 at 8:48

3 Answers 3

2

It should be

/Message/Head/Sender[@Identifier]
                    ^
                    |->no need of / here since Identifier is an attribute of sender

So,

/Message/Head/Sender[@Identifier] would only select Sender if it has an Identifier attribute

/Message/Head/Sender[@Identifier='id'] would only select Sender if it has an Identifier attribute with value id

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

1 Comment

+1. Good explanation. Usual note - if id contains single qoute you'll need to do concat tricks.
1

Here is the wonderful tool to evaluate Xpath of the given XML

go to this link http://www.xmltoolbox.com/ and try to paste your xml in the textarea and move your cursor to the node you want Xpath.Xpath will be generated below

Comments

-1
 XmlIO xml = new XmlIO(xmlPath);
                ProductName = xml.SelectNodeValue(@"//PRODUCTINFO/Application/@ProductName");
                IDictionary<string, string> keyValList = xml.SelectNodesList(@"//PRODUCTINFO/Application/Parameters");

Take a look

Comments

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.