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

时间:2016-05-17 16:48:40

标签: javascript jquery xml object

鉴于此示例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)

1 个答案:

答案 0 :(得分:1)

以下是example如何使用JSONIX将XML解析(解组)到JavaScript中的Swisscom Passeport account

将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);
    });