1

Given this sample XML:

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

I would like to create an object, patient and be able to do something like alert(patient.name.given) and get a popup that says "Bob". My actual data is much more complex than this so I would also need to account for attributes and arrays.

How can this be achieved?

I'm currently using parseXML() but I'd rather not have to type alert($xml.find("patient").find("name").find("given").text)

1 Answer 1

1

Here's an example of how to use JSONIX to parse (unmarshal) XML into JavaScript:

Parse XML into 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);
    });
Sign up to request clarification or add additional context in comments.

5 Comments

I don't understand, what is PO? It looks like something generated by a java utility. Is that required? I don't have a schema or xsd
Yes, Java is required to generate mappings automatically from an XSD, but you can also generate them manually if you don't have an XSD or Java. See Mapping XML to JavaScript Objects
I don't understand why I have to generate or manually create a mapping. I really just want an object that mirrors the XML.
A mapping merely defines what you mean by mirrors the XML.
If the XML file is <document><person><name> then that's what I mirrored. Why do I have to create a mapping that says document { person { name {} } }??

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.