【问题标题】:In XML, is there a way to turn all of a node's children into a single string including the nested XML tags?在 XML 中,有没有办法将节点的所有子节点转换为一个字符串,包括嵌套的 XML 标记?
【发布时间】:2014-04-25 02:21:23
【问题描述】:

我在一个 XML 文件中有如下内容,该文件是仅使用 CSS 和 javascript 的 HTML 页面的数据源。特殊的 XML 代码是我自己的,我想用 javascript 处理它们。

<listitem>regular text could be in here</listitem>
<listitem>possibly with <b>HTML markup</b></listitem>
<listitem>or <special>special xml</special></listitem>

我梦想的是一种从 .getElementsByTagName("listitem") 到以下数组的方法。

["regular text could be in here", "possibly with <b>HTML markup</b>", "or <special>special xml</special>"]

这样,我可以将每个列表项作为数组的一部分进行处理。但是,XML 解析器会分解每个列表项的所有 XML。除了使用 CDATA 会比较乱,还有其他方法吗?

【问题讨论】:

  • 您可以将包含的 &amp;lt; 字符转义为 &amp;lt;,但这也“变得混乱”。正确的答案是将 XML 结构作为 XML 结构来处理,并编写 Javascript 来处理它……或者,如果必须,编写一个 Javascript 函数,将子树序列化为字符串,这样你就可以浪费时间把它分开再次。

标签: html xml parsing children


【解决方案1】:

我认为答案是:

Array.prototype.slice.call(document.getElementsByTagName("listitem")).map(function(x) {return x.innerHTML})

它会返回:

["regular text could be in here", "possibly with <b>HTML markup</b>", "or <special>special xml</special>"]

【讨论】:

  • 谢谢;这在 Mozilla 中效果很好,但在 WebKit(至少 Safari)中效果不佳。见这篇文章:stackoverflow.com/questions/6170911/…。因此解决方案是制作一个 XMLserializer(例如 var mySerializer = new XMLSerializer();)并将代码行末尾的函数替换为 {return mySerializer.serializeToString(x)}。到目前为止我尝试过的所有地方都可以使用。无论如何,一般来说,如果 HTML 实际上是 XHTML(就像我的那样),那么这种方法似乎很容易。 (或者有什么警告吗?)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-20
  • 2011-08-28
  • 2017-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多