使用 jquery 将 xml 文件的外部 xml 结构获取为字符串

Get outer xml structure of xml file to a string with jquery

本文关键字:xml 获取 结构 字符串 外部 jquery 文件 使用      更新时间:2023-09-26

我不知道这是否可能只用javascript/jquery。我有许多 xml 文件,我通常使用 xpath 读取和分发,但 xml 文件是用这样的 HTML 元素构建的:

 <?xml version="1.0" encoding="UTF-8"?>
 <catalog>
 <outcome>
    <title>1.1</title>
    <section>
    <p>some text as an intro:
      <ul>
        <li>part of list</li>
        <li>part of list</li>
      </ul>
    </p>
    <p>more text</p>
    </section>
</outcome>
<outcome>
 <title>1.2</title>
 <section>
    <p>some text as an intro:
      <ul>
        <li>part of list</li>
        <li>part of list</li>
      </ul>
    </p>
    <p>more text</p>
    </section>
</outcome>
</catalog>

我想显示选定元素的所有子元素和后代。使用 javascript,我知道如何加载 xml 并选择我需要的元素,并且我知道如何遍历节点,但是是否可以仅将节点及其后代作为字符串获取?然后我可以只获取字符串并附加一个类似div 的元素.html("字符串")。我会让我的 css 根据需要设置元素样式。这在javascript中可能吗?我知道 xsl 可以作为一个完整的页面来做到这一点,但我只需要一个大 xml 的一小部分。

可以通过将其视为html来使用jQuery来相当简单地做到这一点

$(function() {
  $.get('data.xml', function(xml) {
    $(xml).find('outcome').each(function() {
      $('body').append($(this).html());
    });
  }, 'html');
});

如果您需要在插入新html之前对其进行操作(例如添加类等),那也是失败的微不足道的

演示