Xpath doesn't want to select my tags

I have the following HTML code which contains an address:

            Rotes Rathaus<br />
            Rathausstrasse<br />
            10178 Berlin<br />
            Germany<br />

I'm trying to find the paragraph node that wraps the address (in my case: the <p> tag), and all I have is an array of parts of the address (eg.: 'Rathaus', 'Berlin', '10178').

I'm querying the dom using the following XPath selector:


This works great and returns met the

node. However, when I'm looking based on the postalCode, I don't get any matches:


What do I need to do in order to solve this? Please note that the location of the address can be anywhere on the page.

Best regards, Nicolas





and the pelement will be selected as a result. It means

look for any element node anywhere in the document, but only if there is at least one child text node whose string value contains "10178".

On the other hand, your original expression:



look for any element node anywhere in the document, but only if the first of its child text nodes contains the string "10178".


You are surprised by the result because of the way functions work in XPath 1.0. A function like contains() expects a single node as the first argument. If it is handed a set of nodes, it will only process the first one and ignore the rest.

The other thing you need to understand is that text that is separated by child elements ends up in separate text nodes. So, the text content of P is actually cut up into several text nodes, because of the intervening br elements.

You can check this by evaluating an expression like

//p/node()           |  Find `p` elements anywhere in the document and return all nodes
                        that are their children, regardless of the type of node.

on the document you have shown, and it will return (individual results separated by -------):

            Rotes Rathaus


            10178 Berlin


As you can see, the textual content of p is stored in a separate text node whenever there is a br in between. At this point you should realise that your original expression would have worked if "10178" had happened to be in the first text node, instead of the third. And perhaps you can guess what //p/text()[3] would yield?

Last hint: This changes with XPath 2.0, where more than one item is a true sequence of nodes and where functions will process each node in turn.

Need Your Help

How often should I put NSAutoreleasePools in place?

iphone objective-c ipad memory-leaks nsautoreleasepool

Hey, I am making a cocoa touch static library, And I have this problem:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.