BitsMax
BitsMax

Reputation: 621

How to get the XML Node via XPath

I have a XML :

<?xml version="1.0" encoding="utf-8" ?>
<Root>
    <Class>
        <Room>
            1
        </Room>
        <Subject>
            English
        </Subject>
    </Class>
    <Class>
        <Room>
            2
        </Room>
        <Subject>
            Maths
        </Subject>
    </Class>
</Root>

I am using it as a datasource for my grid , i have used xmldatasource and xpath for that .

PrimaryDataSource = new XmlDataSource();
PrimaryDataSource.EnableCaching = false;
PrimaryDataSource.Data = ClassXML;
return PrimaryDataSource;

and accessing the nodes in client side as: XPath("Room") & XPath("Subject")

Which gives me the values of that particular attributes.

Now i want to get the whole XML root form client side, one Class root only.

<Class>
    <Room>
        1
    </Room>
    <Subject>
        English
    </Subject>
</Class>

Can anybody tell me how can i get it thru XPath or other methods.

Upvotes: 1

Views: 69

Answers (3)

helderdarocha
helderdarocha

Reputation: 23637

You can select all classes using an absolute XPath expression:

/Root/Class

or a descendant axis expression like:

//Class

which will select a node-set containing all classes, independend of their nesting (if there are Class elements deeper in the hierarchy, they will also be selected in this case.

With a positional predicate like the one suggested in the answer by @ErezRobinson, you can select the classes according to their position in a context. The parentheses will place it in a global context. Every slash-separated step in an XPath expression provides a context which limits the scope of the following step or the following predicate. And each predicate reduces the node set by filtering out nodes that don't match the boolean expression inside it. (//Class)[1] is a shortcut for (//Class)[position() = 1]

You can also select a class matching the values of its children nodes with a predicate. To select all Class elements that have a child element Room with the value of 2, you can use:

//Class[Room = '2']

You can also select by Subject:

//Class[Subject = 'Maths']

Finally, once you have a context, you can select other elements within that scope. For example, you can get the Room number when the Subject is English:

//Class[Subject = 'English']/Room

The Class[Subject = 'English'] step in this case just creates a context for the next step, which effectively selects a node or node set.

Upvotes: 0

Roei Finkelstein
Roei Finkelstein

Reputation: 43

Since there is only one root, you can also use XPATH:

/Class

Upvotes: 1

Erez Robinson
Erez Robinson

Reputation: 784

If you want the first "class" just use:

(//Class)[1]

Upvotes: 1

Related Questions