[html] Line Break in XML?

I'm a beginner in web development, and I'm trying to insert line breaks in my XML file. This is what my XML looks like:

<musicpage>
   <song>
      <title>Song Title</title>
      <lyric>Lyrics</lyric>
   </song>

    <song>
      <title>Song Title</title>
      <lyric>Lyrics</lyric>
   </song>

    <song>
      <title>Song Title</title>
      <lyric>Lyrics</lyric>
   </song>

    <song>
      <title>Song Title</title>
      <lyric>Lyrics</lyric>
   </song>
</musicpage>

I want to have line breaks in between the sentences for the lyrics. I tried everything from /n, and other codes similar to it, PHP parsing, etc., and nothing works! Have been googling online for hours and can't seem to find the answer. I'm using the XML to insert data to an HTML page using Javascript.

Does anyone know how to solve this problem?

And this is the JS code I used to insert the XML data to the HTML page:

<script type="text/javascript">

    if (window.XMLHttpRequest) {
    xhttp=new XMLHttpRequest();
} else {
    xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET","xml/musicpage_lyrics.xml",false);
xhttp.send("");
xmlDoc=xhttp.responseXML;

var x=xmlDoc.getElementsByTagName("songs");
for (i=0;i<x.length;i++) {
    document.write("<p class='msg_head'>");
    document.write(x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue);
    document.write("</p><p class='msg_body'>");
    document.write(x[i].getElementsByTagName("lyric")[0].childNodes[0].nodeValue);
    document.write("</p>");
}
</script>

This question is related to html xml parsing line break

The answer is


@icktoofay was close with the CData

<myxml>
    <record>
        <![CDATA[
        Line 1 <br />
        Line 2 <br />
        Line 3 <br />
        ]]>
    </record>
</myxml>

If you are using CSS to style (Not recommended.) you can use display:block;, however, this will only give you line breaks before and after the styled element.


<description><![CDATA[first line<br/>second line<br/>]]></description>

If you use CDATA, you could embed the line breaks directly into the XML I think. Example:

<song>
    <title>Song Title</title>
    <lyric><![CDATA[Line 1
Line 2
Line 3]]></lyric>
</song>

just use &lt;br&gt; at the end of your lines.


At the end of your lines, simply add the following special character: &#xD;

That special character defines the carriage-return character.


<song>
  <title>Song Tigle</title>
  <lyrics>
    <line>The is the very first line</line>
    <line>Number two and I'm still feeling fine</line>
    <line>Number three and a pattern begins</line>
    <line>Add lines like this and everyone wins!</line>
  </lyrics>
</song>

(Sung to the tune of Home on the Range)

If it was mine I'd wrap the choruses and verses in XML elements as well.


In the XML: use literal line-breaks, nothing else needed there.

The newlines will be preserved for Javascript to read them [1]. Note that any indentation-spaces and preceding or trailing line-breaks are preserved too (the reason you weren't seeing them is that HTML/CSS collapses whitespace into single space-characters by default).

Then the easiest way is: In the HTML: do nothing, just use CSS to preserve the line-breaks

.msg_body {
    white-space: pre-line;
}

But this also preserves your extra lines from the XML document, and doesn't work in IE 6 or 7 [2].

So clean up the whitespace yourself; this is one way to do it (linebreaks for clarity - Javascript is happy with or without them [3]) [4]

[get lyric...].nodeValue
    .replace(/^[\r\n\t ]+|[\r\n\t ]+$/g, '')
    .replace(/[ \t]+/g, ' ')
    .replace(/ ?([\r\n]) ?/g, '$1')

and then preserve those line-breaks with

.msg_body {
    white-space: pre; // for IE 6 and 7
    white-space: pre-wrap; // or pre-line
}

or, instead of that CSS, add a .replace(/\r?\n/g, '<br />') after the other JavaScript .replaces.

(Side note: Using document.write() like that is also not ideal and sometimes vulnerable to cross-site scripting attacks, but that's another subject. In relation to this answer, if you wanted to use the variation that replaces with <br>, you'd have to escape <,&(,>,",') before generating the <br>s.)

--

[1] reference: sections "Element White Space Handling" and "XML Schema White Space Control" http://www.usingxml.com/Basics/XmlSpace#ElementWhiteSpaceHandling

[2] http://www.quirksmode.org/css/whitespace.html

[3] except for a few places in Javascript's syntax where its semicolon insertion is particularly annoying.

[4] I wrote it and tested these regexps in Linux Node.js (which uses the same Javascript engine as Chrome, "V8"). There's a small risk some browser executes regexps differently. (My test string (in javascript syntax) "\n\nfoo bar baz\n\n\tmore lyrics \nare good\n\n")


In XML a line break is a normal character. You can do this:

<xml>
  <text>some text
with
three lines</text>
</xml>

and the contents of <text> will be

some text
with
three lines

If this does not work for you, you are doing something wrong. Special "workarounds" like encoding the line break are unnecessary. Stuff like \n won't work, on the other hand, because XML has no escape sequences*.


* Note that &#xA; is the character entity that represents a line break in serialized XML. "XML has no escape sequences" means the situation when you interact with a DOM document, setting node values through the DOM API.

This is where neither &#xA; nor things like \n will work, but an actual newline character will. How this character ends up in the serialized document (i.e. "file") is up to the API and should not concern you.


Since you seem to wonder where your line breaks go in HTML: Take a look into your source code, there they are. HTML ignores line breaks in source code. Use <br> tags to force line breaks on screen.

Here is a JavaScript function that inserts <br> into a multi-line string:

function nl2br(s) { return s.split(/\r?\n/).join("<br>"); }

Alternatively you can force line breaks at new line characters with CSS:

div.lines {
    white-space: pre-line;
}

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to xml

strange error in my Animation Drawable How do I POST XML data to a webservice with Postman? PHP XML Extension: Not installed How to add a Hint in spinner in XML Generating Request/Response XML from a WSDL Manifest Merger failed with multiple errors in Android Studio How to set menu to Toolbar in Android How to add colored border on cardview? Android: ScrollView vs NestedScrollView WARNING: Exception encountered during context initialization - cancelling refresh attempt

Examples related to parsing

Got a NumberFormatException while trying to parse a text file for objects Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) Python/Json:Expecting property name enclosed in double quotes Correctly Parsing JSON in Swift 3 How to get response as String using retrofit without using GSON or any other library in android UIButton action in table view cell "Expected BEGIN_OBJECT but was STRING at line 1 column 1" How to convert an XML file to nice pandas dataframe? How to extract multiple JSON objects from one file? How to sum digits of an integer in java?

Examples related to line

How do I compute the intersection point of two lines? Java Replace Line In Text File draw diagonal lines in div background with CSS How to make a new line or tab in <string> XML (eclipse/android)? How do you run a command for each line of a file? How can I format a list to print each element on a separate line in python? Remove lines that contain certain string How to paste text to end of every line? Sublime 2 Making PHP var_dump() values display one line per value How to do multiple line editing?

Examples related to break

How to break a while loop from an if condition inside the while loop? illegal use of break statement; javascript How can I use break or continue within for loop in Twig template? break statement in "if else" - java Regarding Java switch statements - using return and omitting breaks in each case Is it bad practice to use break to exit a loop in Java? break/exit script Breaking out of a for loop in Java How to break out of while loop in Python? How to kill a while loop with a keystroke?