假设我们有以下的XML数据:

<books>
  <book>
    <title>The Catcher in the Rye</title>
    <author>J.D. Salinger</author>
    <published>1951</published>
  </book>
  <book>
    <title>To Kill a Mockingbird</title>
    <author>Harper Lee</author>
    <published>1960</published>
  </book>
</books>

我们可以使用xml2js库将其转换成JS对象:

const xml2js = require('xml2js');

const xmlData = `
<books>
  <book>
    <title>The Catcher in the Rye</title>
    <author>J.D. Salinger</author>
    <published>1951</published>
  </book>
  <book>
    <title>To Kill a Mockingbird</title>
    <author>Harper Lee</author>
    <published>1960</published>
  </book>
</books>
`;

xml2js.parseString(xmlData, (err, result) => {
  if (err) {
    console.error(err);
  } else {
    console.log(result);
  }
});

输出结果:

{
  books: {
    book: [
      {
        title: ['The Catcher in the Rye'],
        author: ['J.D. Salinger'],
        published: ['1951']
      },
      {
        title: ['To Kill a Mockingbird'],
        author: ['Harper Lee'],
        published: ['1960']
      }
    ]
  }
}

我们可以将其使用Vue渲染:

<template>
  <div>
    <h1>Books:</h1>
    <ul>
      <li v-for="book in books" :key="book.title">
        <h2>{{ book.title }}</h2>
        <p>Author: {{ book.author }}</p>
        <p>Published: {{ book.published }}</p>
      </li>
    </ul>
  </div>
</template>

<script>
import xml2js from 'xml2js';

export default {
  data() {
    return {
      books: []
    }
  },
  mounted() {
    const xmlData = `
      <books>
        <book>
          <title>The Catcher in the Rye</title>
          <author>J.D. Salinger</author>
          <published>1951</published>
        </book>
        <book>
          <title>To Kill a Mockingbird</title>
          <author>Harper Lee</author>
          <published>1960</published>
        </book>
      </books>
    `;

    xml2js.parseString(xmlData, (err, result) => {
      if (err) {
        console.error(err);
      } else {
        this.books = result.books.book.map(b => ({
          title: b.title[0],
          author: b.author[0],
          published: b.published[0],
        }));
      }
    });
  }
}
</script>
写出一个xml转JS的代码示例用vue。

原文地址: https://www.cveoy.top/t/topic/bHcp 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录