开发者

An XPath 1.0 query that handles two cases

开发者 https://www.devze.com 2023-03-26 16:23 出处:网络
I\'m not very experienced in XPaths but I have tried a good while and searched alot without coming up with a solution.

I'm not very experienced in XPaths but I have tried a good while and searched alot without coming up with a solution.

I'm extracting information from XHTML that mostly looks something like

<html>
    <head></head>
    <body>
        <div class="preamble">
            <p>Some text 1</p>
        </div>
        <h1>Some headline</h1>
        <p>Some other text</p>
    </body>
</html>

What I'm mostly interested in is the text contained in the preamble div, which exists in most of my documents. The problem is the ones lacking the div, in these cases I'd like to extract the other text under the body tag.

In this case I'd like to get "Some text 1" b开发者_JAVA技巧ut if there was no div I'd be ok with "Some headline Some other text" or something.

With XPath 2.0 it's no problem, but circumstances limits me to the functionality in the "core" 1.0 set.

My question is whether this behaviour is possible in one XPath 1.0 query, or whether I should give up on it?

Regards /Magnus


Try this XPath:

//div[@class = 'preamble'] 
    | //body/*[not(preceding-sibling::div[@class = 'preamble']) 
        and not(self::div[@class = 'preamble'])]


Since XPath 1.0 does not specify an ordering for nodesets, you want to ensure that your two cases are exclusive.

string( /html/body/div[@class='preamble'] | /html/body[not(div[@class='preamble'])] )

If your XPath processor returns nodesets in document order, a simpler query will do:

string( (/html/body/div[@class='preamble'] | /html/body)[last()] )


I think you neet this XPath 1.0:

"/html/body/div[@class='preamble']//text()
|
/html/body[not(div/@class='preamble')]//text()"

The first location path select all text nodes inside the div. The other will select all text nodes inside a body without that div. The union (|) of both will select the wanted text.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号