1
votes

I have a GridView populated from an xml file, which has the following structure:

<menu>
  <item id="1" name="home" page="default.aspx">
     *{...some stuff...}*
  <item>
  <item id="2" name="content" page="content.aspx">
     *{...some stuff...}*
  <item>
  <item id="3" name="user" page="user.aspx">
     *{...some stuff...}*
  <item>
<menu>

As you can reckon, it's the menu of my application.

If i just associate that file to an xmldatasource and then to a GridView, it shows (correctly) a grid like this:

id name page

1 home default.aspx

2 content content.aspx

3 user user.aspx3 user user.aspx

How do I set the xPath query to only show name attribute/field?

I've tried those:

  1. menu/item@name
  2. menu/@name
  3. //@name

but didn't work

1
Good question, +1. See my answer for an explanation of the problem and a complete solution. :) - Dimitre Novatchev
I think this is not an XPath question but MS Databinding question. From msdn.microsoft.com/en-us/library/aa479341.aspx : it looks like you need to set AutoGenerateColumns="False" attribute of asp:GridView element, and then use Columns and asp:BoundField childs. - user357812

1 Answers

0
votes

I have a GridView populated from an xml file, which has the following structure:

<menu> 
  <item id="1" name="home" page="default.aspx"> 
     *{...some stuff...}* 
  <item> 
  <item id="2" name="content" page="content.aspx"> 
     *{...some stuff...}* 
  <item> 
  <item id="3" name="user" page="user.aspx"> 
     *{...some stuff...}* 
  <item> 
<menu>

This is not a well-formed XML file -- an ending tag must have the sintax </tag> and there are no ending tags at all in the above text.

How do I set the xPath query to only show name attribute/field?

I've tried those:

  1. menu/item@name
  2. menu/@name
  3. //@name
  1. is syntactically invalid: location steps must start with the / character and there is no / character between item and @name.

  2. is syntactically valid but is asking to select all name attributes of all menu elements that are children of the current node. Unfortunately, menu has no name attributes.

  3. should select nodes, but given the text above isn't at all a well-formed XML document, this explains the negative result. Also, this selects all name attributes in the whole document, regardles on which element they are -- this is not exactly what you want, regardless of the fact that on a wellformed document of this type this might select the nodes you want.

Solution:

Step1: Correct your XML document:

<menu>
  <item id="1" name="home" page="default.aspx">
     *{...some stuff...}*
  </item>
  <item id="2" name="content" page="content.aspx">
     *{...some stuff...}*
  </item>
  <item id="3" name="user" page="user.aspx">
     *{...some stuff...}*
  </item>
</menu>

Step2: Use one of the following XPath expressions (there are even more that would select the wanted nodes):

/menu/item/@name

or

/*/item/@name

or

/*/*/@name

or

//@name