import XML to HTML

import XML to HTML

本文关键字:HTML to XML import      更新时间:2023-09-26

我有一个XML字符串,表示一些HTML标签。我想选择一些XML并将其导入HTML中。

我目前正在做的事情的一个例子:

<html>
<head>
   <meta charset="utf-8">
   <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<div><p>som text</p></div>
<h1>hi there</h1>
<button>click</button>
<script>
   xml = '<?xml version="1.0" encoding="utf-8"?><root><html><a href="#">the new link</a></html></root>';
   $xml =$($.parseXML( xml ));
$('button').on('click',function(){
    var content = $xml.find('html:first').contents();
    content.appendTo('body');
});
</script>
</body>
</html>

代码应该在页面末尾附加一个链接,但我只能看到文本,它没有链接。没有 HTML 标记有效。

我使用另一个库来执行此操作,而不是像 https://github.com/jindw/xmldom 那样的jQuery,但结果是相同的。更新 : 这是 JSFIDDLE 链接 : http://jsfiddle.net/V4gHz/

最后,我找到了自己问题的答案。 问题是不要浪费你的时间在innerHTML或XMLSerializer上。 因为它们不适用于所有浏览器,并且仅与Firefox兼容。 像$.content()或$.HTML()这样的jquery解决方案也只适用于Firefox,不适用于Opera,Chrome和IE。

我找到一个名为"HTMLize"的jQuery插件,它是真正的序列化程序。 插件地址是: https://github.com/ZeeAgency/jquery.htmlize

你可以从GitHub找到更多信息。 这就是我的问题解决的方式:

<html>
<head>
<meta charset="utf-8">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
 </head>
 <body>
  <div><p>som text</p></div>
  <h1>hi there</h1>
  <button>click</button>
  <script>
    xml = '<?xml version="1.0" encoding="utf-8"?><root><html><a href="#">the new link</a></html></root>';
    $xml =$($.parseXML( xml ));
 $('button').on('click',function(){
    var content = $xml.find('html:first').htmlize();
     $(content).appendTo('body');
 });
 </script>
</body>
</html>