将XML转换为普通的旧JavaScript对象

Convert XML to plain old JavaScript object?

本文关键字:JavaScript 对象 XML 转换      更新时间:2023-09-26

给定此示例XML:

  <patient>
    <name>
      <given>Bob</given>
      <family>Dole</family>
    </name>
  </patient>

我想创建一个对象patient,并能够做一些类似alert(patient.name.given)的事情,然后得到一个弹出窗口,上面写着"Bob"。我的实际数据比这复杂得多,所以我还需要考虑属性和数组。

如何做到这一点?

我目前正在使用parseXML(),但我不想键入alert($xml.find("patient").find("name").find("given").text)

以下是如何使用JSONIX将XML解析(解组)为JavaScript:的示例

将XML解析为JS

// Include or require PO.js so that PO variable is available
// For instance, in node.js:
var PO = require('./mappings/PO').PO;
// First we construct a Jsonix context - a factory for unmarshaller (parser)
// and marshaller (serializer)
var context = new Jsonix.Context([PO]);
// Then we create a unmarshaller
var unmarshaller = context.createUnmarshaller();
// Unmarshal an object from the XML retrieved from the URL
unmarshaller.unmarshalURL('po.xml',
    // This callback function will be provided
    // with the result of the unmarshalling
    function (unmarshalled) {
        // Alice Smith
        console.log(unmarshalled.value.shipTo.name);
        // Baby Monitor
        console.log(unmarshalled.value.items.item[1].productName);
    });