user421814
user421814

Reputation: 605

Explain xpath and xquery in simple terms

I am new to programming. I know what XML is. Can anyone please explain in simple terms what xpath and xquery do Where are they used?

Upvotes: 8

Views: 9017

Answers (2)

John Nickerson
John Nickerson

Reputation: 203

XPath is a way of locating specific elements in an XML tree.

For instance, given the following structure:

<myfarm>
  <animal type="dog">
    <name>Fido</name>
    <color>Black</color>
  </animal>
  <animal type="cat">
    <name>Mitsy</name>
    <color>Orange</color>
  </animal>
</myfarm>

XPath allows you to traverse the structure, such as:

/myfarm/animal[@type="dog"]/name/text()

which would give you "Fido"

XQuery is an XML query language that makes use of XPath to query XML structures. However it also allows for functions to be defined and called, as well as complex querying of data structures using FLWOR expressions. FLWOR allows for join functionality between data sets defined in XML. FLWOR article from wikipedia

Sample XQuery (using some XPath) is:

declare function local:toggle-boolean($b as xs:string) 
as xs:string 
{
    if ($b = "Yes") then "true"
    else if ($b = "No") then "false"
    else if ($b = "true") then "Yes"
    else if ($b = "false") then "No"
    else "[ERROR] @ local:toggle-boolean"
};

<ResultXML>
    <ChangeTrue>{ local:toggle-boolean(doc("file.xml")/article[@id="1"]/text()) }</ChangeTrue>
    <ChangeNo>{ local:toggle-boolean(doc("file.xml")/article[@id="2"]/text()) }</ChangeNo>
</ResultXML>

Upvotes: 15

Gaim
Gaim

Reputation: 6844

XPath is a simple query language which serves to search in XML DOM. I think that it can be compared to SQL Select statements with databases. XPath can evaluate many programs which work with XML and has a mass usage. I recommend u to learn it.

XQuery is much more powerful and complicated it also offers many options how to transform result, it offers cycles etc. But also it is query language. It is also used as query language into XML databases. I think that this language has only specific usage and probably is not necessary to know it, in the beginning there will be enough if u know that it exists and what it can

There is simple explanation I hope that it is enough and understandable

Upvotes: 5

Related Questions