473,796 Members | 2,632 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

XPath querying text node *including* <br/>

Dear all,

I'm trying to extract data from HTML using XPath in Java.
Unfortunately the text contents of nodes may contain <br/tags which
are not correctly interpreted, at least not for me ;)

A <pnode may contain this text:

<p>
Test1<br/>
Test2<br/>
Test3
</p>

Which is returned by the XPath query as "Test1Test2Test 3" but I need
it as "Test1\nTest2\n Test3" or "Test1 Test2 Test3".

Here's example code (Java 6):

public class Example {
private static final String html = "<html><body><p >Test1<br/
>Test2<br/>Test3</p></body></html>";
public static void main( String[] args ) throws Exception {
final XPathFactory xPathFactory = XPathFactory.ne wInstance();

XPath xPath = xPathFactory.ne wXPath();
String value = (String)xPath.e valuate(
"//p",
new InputSource( new StringReader( html ) ),
XPathConstants. STRING );

System.out.prin tln( value );

xPath = xPathFactory.ne wXPath();
value = (String)xPath.e valuate(
"//p/text()",
new InputSource( new StringReader( html ) ),
XPathConstants. STRING );

System.out.prin tln( value );

xPath = xPathFactory.ne wXPath();
value = (String)xPath.e valuate(
"//p/node()",
new InputSource( new StringReader( html ) ),
XPathConstants. STRING );

System.out.prin tln( value );
}
}

This code returns:

Test1Test2Test3
Test1
Test1

Is there any way (XPath function etc) which will return the contents
as desired?

Thank you!
Jun 27 '08 #1
8 13201
* Sven wrote in comp.text.xml:
>I'm trying to extract data from HTML using XPath in Java.
Unfortunatel y the text contents of nodes may contain <br/tags which
are not correctly interpreted, at least not for me ;)
You have to convert them to line breaks yourself, using XPath 1.0 there
is no way to transform them to line breaks with a simple expression. It
would be easy to do with XSLT, otherwise you have to implement this in
code. If you don't have other child elements you could simply iterate
over the children of the element, append text to a buffer and if you
have a br element instead, append a line break to the buffer.
--
Björn Höhrmann · mailto:bj****@h oehrmann.de · http://bjoern.hoehrmann.de
Weinh. Str. 22 · Telefon: +49(0)621/4309674 · http://www.bjoernsworld.de
68309 Mannheim · PGP Pub. KeyID: 0xA4357E78 · http://www.websitedev.de/
Jun 27 '08 #2
Sven wrote:
Dear all,

I'm trying to extract data from HTML using XPath in Java.
Unfortunately the text contents of nodes may contain <br/tags which
are not correctly interpreted, at least not for me ;)

A <pnode may contain this text:

<p>
Test1<br/>
Test2<br/>
Test3
</p>

Which is returned by the XPath query as "Test1Test2Test 3" but I need
it as "Test1\nTest2\n Test3" or "Test1 Test2 Test3".

Here's example code (Java 6):

public class Example {
private static final String html =
"<html><body><p >Test1<br/Test2<br/Test3</p></body></html>";

}

This code returns:

Test1Test2Test3
Test1
Test1

Is there any way (XPath function etc) which will return the contents
as desired?

Thank you!
String sanitized = html.replaceAll ("<br/>","\n");
and then replace you usages of `html' with those of `sanitized'.

--
Beware of bugs in the above code; I have only proved it correct, not
tried it. -- Donald E. Knuth
Jun 27 '08 #3
Joshua Cranmer a écrit :
String sanitized = html.replaceAll ("<br/>","\n");
and then replace you usages of `html' with those of `sanitized'.
Hi,

This usually doesn't work for thousand different reasons, for examples :

<br></br>
<!-- this <br/isn't a line break -->
<![CDATA[this <br/isn't a line break]]>
<br><?todo : buy some <br/>ead?></br>

etc...

This is the main reason why we have to use parsers : this way, one can
process things for what they are rather than for what they look like.

With a SAX filter you can have a more verbose code, but correct :

public class LineBreakFilter extends XMLFilterImpl {
public void startElement(St ring uri, String localName, String
qName, Attributes atts) {
if ( "br".equals(loc alName) ) {
characters("\n" .toCharArray(), 0, 1);
} else {
super.startElem ent(...);
}
}
public void endElement(Stri ng uri, String localName, String qName) {
if ( ! "br".equals(loc alName) ) {
super.endElemen t(...);
} // else do nothing
}
}

You just have to plug it to a SAX parser (beware to namespaces if you
have some).

--
Cordialement,

///
(. .)
--------ooO--(_)--Ooo--------
| Philippe Poulard |
-----------------------------
http://reflex.gforge.inria.fr/
Have the RefleX !
Jun 27 '08 #4
Philippe Poulard a écrit :
public class LineBreakFilter extends XMLFilterImpl {
public void startElement(St ring uri, String localName, String qName,
Attributes atts) {
if ( "br".equals(loc alName) ) {
characters("\n" .toCharArray(), 0, 1);
} else {
super.startElem ent(...);
}
}
public void endElement(Stri ng uri, String localName, String qName) {
if ( ! "br".equals(loc alName) ) {
super.endElemen t(...);
} // else do nothing
}
}
I forgot to add in the test: && uri == null (or && uri.length == 0, I
don't remember what the SAX parser is supposed to give)

--
Cordialement,

///
(. .)
--------ooO--(_)--Ooo--------
| Philippe Poulard |
-----------------------------
http://reflex.gforge.inria.fr/
Have the RefleX !
Jun 27 '08 #5
On 28 Apr., 00:11, Joshua Cranmer <Pidgeo...@veri zon.invalidwrot e:
String sanitized = html.replaceAll ("<br/>","\n");
and then replace you usages of `html' with those of `sanitized'.
Thanks for the hint! Although Philippe noted that this may not work in
all situations it's sufficient enough for me at the moment.

Now I have another problem with text nodes (damn text nodes *g*).
Still the same scenario where I try to extract data from XHTML pages,
let's assume we have nodes like this

<div>
Text1
<a href="http://...">Link</a>
Text2
</div>

Then \\div\text() will only return "Text1". It's basically the same
problem where text nodes are interrupted by child nodes. Any way with
pure XPath to fetch the whole text?

Thanks!
Jun 27 '08 #6
<div>
Text1
<a href="http://...">Link</a>
Text2
</div>

Then \\div\text() will only return "Text1".
//div/text() (note: FORWARD slashes in XPath!) will return two text
nodes. Whatever you are doing with the result of that path may be
operating on only the first node returned, but you didn't show us that
which makes it hard to advise you.

Alernatively, you could retrieve the text value of the <divelement --
but that would include Link as well, since it's defined as all contained
text.
Jun 27 '08 #7
Sven wrote:
<div>
Text1
<a href="http://...">Link</a>
Text2
</div>

Then \\div\text() will only return "Text1". It's basically the same
problem where text nodes are interrupted by child nodes. Any way with
pure XPath to fetch the whole text?
Well
string(/div)
will give you the text contained in that element which is
"
Text1
Link
Text2
"

And
/div/text()
as an XPath 1.0 expression selects two text nodes over which you can
iterate to extract
"
Text1
"
and
"
Text2
"
--

Martin Honnen
http://JavaScript.FAQTs.com/
Jun 27 '08 #8
On 23 Mai, 19:33, "Joseph J. Kesselman" <keshlam-nos...@comcast. net>
wrote:
//div/text() (note: FORWARD slashes in XPath!) will return two text
nodes. Whatever you are doing with the result of that path may be
operating on only the first node returned, but you didn't show us that
which makes it hard to advise you.
Thanks, this was my bad! In Java I used XPath#evaluate( String
expression, InputSource source, QName returnType ) with returnType ==
XPathConstants. STRING which apparently doesn't concatenate multiple
results. I'm now using XPathConstants. NODESET and everything works as
expected. Great!
Jun 27 '08 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
7866
by: fis | last post by:
Hi all, I've problem because there are needed break lines in my texts on the web site but i can't do it :( My pipeline looks like: XMS -> I18N -> XSLT -> HTML I have lot of texts in my "languages" files and these are describes for things on my website. Example text looks like this:
2
1948
by: John D | last post by:
can anyone explain why a site would use this in their page <!--<BR>--> Presumably it is hiding the <BR> from ... ??? TIA John
9
43160
by: Wayne | last post by:
$a = $_POST; # txt_content = This is a<CR><LF>Test $p = str_replace ("%0D%0A", "<br>", $a); That is the above code that I am using, however, it is not picking up the CR/LF from the textarea. I have also attempted singular variations of the CR/LF combination and even reversed the sequence without success. Is it possible that it may be encoded differently and if so what is it? Thanks
1
1904
by: Jeff | last post by:
hey asp.net 2.0 In my website I've got a textbox with TextMode=MultiLine. The user can enter text that contain "new line"... But to displays this I'm also using a textbox with TextMode=MultiLine and ReadOnly=True. The textbox displays a ugly border arround the textbox, including scrollbars
14
3162
by: Michael | last post by:
Since the include function is called from within a PHP script, why does the included file have to identify itself as a PHP again by enclosing its code in <?php... <?> One would assume that the PHP interpreter works like any other, that is, it first expands all the include files, and then parses the resulting text. Can anyone help with an explanation? Thanks, M. McDonnell
10
3203
by: Summercoolness | last post by:
so i am starting to use more of <br /and <div style="clear: both" / which is the XHTML style... now, won't those actually confuse the old browsers? for example, will the old browser treat the "div" as not closing, and so everything after the div will be treated as part of that div?
6
2391
by: JoeS | last post by:
I'm new to XSLT, it what our old website developer used but he has now left our company. I have been given the task of making our site output as valid XHTML as I can get it. Currently in the .XSL files I write self-closing tags like <br/> but in the output XHTML they come out as <br> and therefore the page doesn't validate. This happens for other self-closing tags like <img src=""/> too. I don't really know XSLT so I don't know how I can fix...
7
3628
by: Nathan Sokalski | last post by:
Something that I recently noticed in IE6 (I don't know whether it is true for other browsers or versions of IE) is that it renders <br/and <br></br> differently. With the <br/version, which is what most people use when they write static code (some people use <br>, but with xhtml you are required to close all tags), IE6 simply breaks to the next line like it is supposed to. However, with <br></br>, which is what is sometimes generated by...
0
9528
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10455
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10228
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10173
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10006
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9052
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5441
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4116
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3731
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.