Xpath: contains () for the response group

I'm trying to learn XPath, and I'm having trouble doing a nested search (using contains).

In particular, I was asked the following question:

There is a list of authors and a list of books according to the following dtd:

<!ELEMENT db1 (book*, author*)> <!ELEMENT book (title)> <!ATTLIST book bid ID #REQUIRED authors IDREFS #REQUIRED > <!ELEMENT title (#PCDATA)> <!ELEMENT author (#PCDATA)> <!ATTLIST author aid ID #REQUIRED > 

Write an XPath expression that returns the number of authors who wrote books. It can be assumed that there are no two author identifiers that contain each other.

I have tried many things, but I keep getting the error message "Too many elements in the composition." I am trying to run something like this:

 //author/@aid[contains(//book/@authors/string(.), string(.))] 

As an example, I use the following XML file:

 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE db1 SYSTEM "C:\blabla\db1.dtd"> <db1> <book authors="a1 a3 a4" bid="b1"> <title>Book 1</title> </book> <book authors="a1 a2 a3" bid="b2"> <title>Book 2</title> </book> <book authors="a4" bid="b3"> <title>Book 3</title> </book> <author aid="a1"></author> <author aid="a91"></author> <author aid="a2"></author> <author aid="a88"></author> <author aid="a3"></author> <author aid="a4"></author> <author aid="a5"></author> <author aid="a6"></author> </db1> 

The expected answer should be

 a1 a2 a3 a4 

Any tips?

Thanks.

+4
source share
1 answer

I found the answer I was looking for. This is actually not that difficult, you just need to be familiar with the XPath id function.

XPAth request for this: count(id(//book/@authors))

The list of authors can be specified as id(//book/@authors) . Note that this xquery returns the full xml (and not just the names):

 <author aid="a1"/> <author aid="a2"/> <author aid="a3"/> <author aid="a4"/> 

See link .

In this case, the contains function is not applicable, but, fortunately, it is also not needed.

The id function selects elements by their unique identifier. When the id argument is of type node-set, then the result is the union of the result of applying id to the string value of each of the nodes in the node-set argument. When the id argument is of any other type, the argument is converted to a string, as if invoking a string function; the string is divided into a list of tokens, separated by spaces (spaces - any sequence of characters corresponding to the product S); the result is a node-set containing the elements in the same document as the node context, which has a unique identifier equal to any of the tokens in the list.

+2
source

Source: https://habr.com/ru/post/1299563/


All Articles