在JavaScript中,如何将DOM的一部分序列化到XHTML? [英] In JavaScript, how can serializer part of the DOM to XHTML?

查看:161
本文介绍了在JavaScript中,如何将DOM的一部分序列化到XHTML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将DOM的一部分序列化为XHTML(有效的XML)。假设我在< body> 中只有一个元素,这是我想序列化的元素:

 < DIV> 
< hr>
< img src =/ foo.png>
< / div>

这样, document.innerHTML 给我几乎是我想要的,除了它返回HTML,而不是XHTML(即< hr> < img> 不会正确关闭)。因为 innerHTML 没有做这个诀窍,那么我该怎么把DOM的部分序列化到XHTML?

解决方案

我不确定是否使用其他语言(在JavaScript引擎上)是一个选项。如果这有任何帮助,这将是XQuery(XQIB)的方式:

 < script type =应用/ XQuery的> 
serialize(b:dom()// div)
< / script>

例如,在下一页中,序列化的XHTML是作为文本写在页面上而不是脚本标签,在div标签之后:

 <!DOCTYPE html> 
< html xmlns =http://www.w3.org/1999/xhtml>
< head>
< title>序列化部分DOM< / title>
< meta charset =UTF-8/>
< script type =text / javascriptsrc =mxqueryjs / mxqueryjs.nocache.js>< / script>
< / head>
< body>
< div>
< hr>
< img src =/ foo.png>
< / div>
< script type =application / xquery>
serialize(b:dom()// div)
< / script>
< / body>
< / html>

HTML DOM被映射到XQuery数据模型(XML之上的数据模型)。 b:dom()返回页面的文档节点,并且// div导航到所有后代的div标签。然后,序列化函数将其序列化为一个字符串。



但是,这将适用于IE9 +(不是6+)和最新版本的Chrome,Firefox,Safari,Opera。 / p>

I would like to serialize part of the DOM to XHTML (valid XML). Let's assume I have just one element inside <body>, and that this is the element I want to serialize:

<div>
    <hr>
    <img src="/foo.png">
</div>

With this, document.innerHTML gives me almost what I want, except it returns HTML, not XHTML (i.e. the <hr> and <img> won't be properly closed). Since innerHTML doesn't do the trick, how can I serialize part of the DOM to XHTML?

解决方案

I am not sure if using another language (on top of the JavaScript engine) is an option. If this is of any help, this would be the XQuery (XQIB) way of doing it:

<script type="application/xquery">
  serialize(b:dom()//div)
</script>

For example, in the following page, the serialized XHTML is written as text on the page instead of the script tag, after the div tag:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>   
    <title>Serializing part of the DOM</title>
    <meta charset="UTF-8"/>
    <script type="text/javascript" src="mxqueryjs/mxqueryjs.nocache.js"></script>
  </head>
  <body>
    <div>
      <hr>
      <img src="/foo.png">
    </div>
    <script type="application/xquery">
      serialize(b:dom()//div)
    </script>
  </body>
</html>

The HTML DOM is mapped to the XQuery data model (a data model on top of XML). b:dom() returns the document node of the page, and //div navigates to all descendant div tags. The serialize function then serializes this to a string.

However, this will work for IE9+ (not 6+) and recent versions of Chrome, Firefox, Safari, Opera.

这篇关于在JavaScript中,如何将DOM的一部分序列化到XHTML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆