I am trying to parse this XML:
<?xml version="1.0" encoding="UTF-8"?>
<veranstaltungen>
<veranstaltung id="201611211500#25045271">
<titel>Mal- und Zeichen-Treff</titel>
<start>2016-11-21 15:00:00</start>
<veranstaltungsort id="20011507">
<name>Freizeitclub - ganz unbehindert </name>
<anschrift>Macht los e.V.
Lipezker Straße 48
03048 Cottbus
</anschrift>
<telefon>xxxx xxxx </telefon>
<fax>0355 xxxx</fax>
[...]
</veranstaltungen>
As you can see, some of the texts have whitespace or even linebreaks. I am having issues with the text from the node anschrift, because I need to find the right location data in a database. Problem is, the returned String is:
Macht los e.V.Lipezker Straße 4803048 Cottbus
instead of:
Macht los e.V. Lipezker Straße 48 03048 Cottbus
I know the correct way to parse it should be with normalie-space() but I cannot quite work out how to do it. I tried this:
// Does not work; afaik because xpath 1 normalizes just the first node
xPath.compile("normalize-space(veranstaltungen/veranstaltung[position()=1]/veranstaltungsort/anschrift/text()"));
// Does not work
xPath.compile("veranstaltungen/veranstaltung[position()=1]/veranstaltungsort[normalize-space(anschrift/text())]"));
I also tried the solution given here: xpath-normalize-space-to-return-a-sequence-of-normalized-strings
xPathExpression = xPath.compile("veranstaltungen/veranstaltung[position()=1]/veranstaltungsort");
NodeList result = (NodeList) xPathExpression.evaluate(doc, XPathConstants.NODESET);
String normalize = "normalize-space(.)";
xPathExpression = xPath.compile(normalize);
int length = result.getLength();
for (int i = 0; i < length; i++) {
System.out.println(xPathExpression.evaluate(result.item(i), XPathConstants.STRING));
}
System.out prints:
Macht los e.V.Lipezker Straße 4803048 Cottbus
What am I doing wrong?
Update
I have a workaround already, but this can't be the solution. The following few lines show how I put the String together from the HTTPResponse:
try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), Charset.forName(charset)))) {
final StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
// stringBuilder.append(line);
// WORKAROUND: Add a space after each line
stringBuilder.append(line).append(" ");
}
// Work with the red lines
}
I would rather have a solid solution.
normalize-space()strips leading and trailing whitespace and converts other sequences of whitespace characters (including newlines) into a single space character. As your result doesn't have a space between the lines of the text content of theanschriftelement, something must eat your newlines beforenormalize-space()gets to do its job.