XPath - Querying two XML documents
I have have two xml docs:
XML1:
<Books>
<Book id="11">
.......
<AuthorName/>
</Book>
......
</Books>
XML2:
<Authors>
<Author>
<BookId>11</BookId>
<AuthorName>Smith</AuthorName>
</Author>
</Authors>
I'm trying to do the following:
G开发者_如何学JAVAet the value of XML2/Author/AuthorName where XML1/Book/@id equals XML2/Author/BookId.
XML2/Author/AuthorName[../BookId = XML1/Book/@id]
An XPath 1.0 expression cannot refer to more than one XML document, unless the references to the additional documents have been set up in the context of the XPath engine by the hosting language. For example, if XSLT is the hosting language, then it makes its document()
function available to the XPath engine it is hosting.
document($xml2Uri)/Authors/Author[BookId = $mainDoc/Books/Book/@id]
Do note, that even the main XML document needs to be referenced via another <xsl:variable>
, named here $mainDoc
.
The document()
function is available only if Xpath is hosted by XSLT! This is not mentioned in the answer of Doc Brown and is misleading the readers.
An XPath 2.x expression may refer to any additional XML document using the XPath 2.0 doc()
function.
for $doc in /,
$doc2 in doc(someUri)
return
$doc2/Authors/Author[BookId = $doc/Books/Book/@id]
The document
function is your friend, here is a short tutorial how to combine multiple input files.
EDIT: Of course, that works only if your are using Xpath in an Xslt script.
精彩评论