I have an XML document with some sample content like this:
<someTag>
<![CDATA[Hello World]]>
</someTag>
I'm parsing the above XML in Jav开发者_如何学CaScript. When I try access and render the Hello World text using xmldoc.getElementsByTagName("someTag")[0].childNodes[0].textContent
all I get was a blank text on screen.
The code is not returning undefined
or any error messages. So I guess the code is properly accessing the message. But due to CDATA
, it is not rendering properly on screen.
Anyway to fix the issue and get the Hello World out of this xml file?
Note that Firefox's behaviour is absolutely correct. someTag
has three children:
- A
Text
node containing the whitespace between the<someTag>
and<!CDATA
. This is one newline and one space; - the
CDATASection
node itself; - another whitespace
Text
node containing the single newline character between the end of the CDATA and the close-tag.
It's best not to rely closely on what combination of text and CDATA nodes might exist in an element if all you want is the text value inside it. Just call textContent
on <someTag>
itself and you'll get all the combined text content: '\n Hello World\n'
. (You can .trim()
this is you like.)
If you're running Firefox, maybe this is the issue you're having. The behavior looks very similair... The following might do the trick:
xmldoc.getElementsByTagName("someTag")[0].childNodes[1].textContent;
精彩评论