# oxm

> Round-tripable Object-XML mapper. Using knockout.js observables, you can bind the values to your view too.

Latest version **5.0.2** (published 2017-01-20) · ISC license · 0 weekly downloads

## Install

```sh
npm install oxm
pnpm add oxm
yarn add oxm
bun add oxm
```

## Health

**Score 15/100 (F)** — status: abandoned.

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 5.0.2 |
| Published | 2017-01-20 |
| First published | 2017-01-12 |
| Weekly downloads | 0 |
| License | ISC |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 1 |
| Known vulnerabilities | 0 (+16 in 1 direct dependencies) |
| Install scripts | no |
| Author | Istvan Sipos |
| Maintainers | ccsistvan |

## Links

- npm: https://www.npmjs.com/package/oxm
- Repository: https://gitlab.com/ccsistvan/oxm
- Homepage: https://gitlab.com/ccsistvan/oxm#README
- Issues: https://gitlab.com/ccsistvan/oxm/issues
- npm.io page: https://npm.io/package/oxm

## Dependencies (1)

- [xmldom](https://npm.io/package/xmldom.md) ^0.1.27

## Recent versions

- 5.0.2 (latest) — 2017-01-20
- 5.0.1 — 2017-01-20
- 5.0.0 — 2017-01-20
- 1.0.0 — 2017-01-12

## README

# OXM

Round-tripable Object-XML mapper.
Using knockout.js observables, you can bind the values to your view too.


## Terms

### accessor
Function which sets or gets the value of a variable.

### data
OXM wrapped **accessor**, storing a single value.

### list
OXM wrapped **accessor**, storing a list of similar **oxm objects**.

### complex
OXM wrapped **accessor**, storing an Object.

### oxm object
A **data**, **list** or **complex**.

## Exported methods

### xml

_xml(obj)_

Returns the xml string representing the data stored in the _obj_ **oxm_object**.

_xml(obj, xml)_

Parses the _xml_ [string] and updates the value of the _obj_ **oxm_object**.


### data

_data(acc, tag)_

Extends the _acc_ **accessor**, and sets the tagnName of its xml representation to _tag_.
_acc_ will be used as a **data** object.

### list

_list(acc, tag, Child)_

Extends the _acc_ **accessor**, and sets the tagnName of its xml representation to _tag_.
_acc_ will be used as a **list** object.
_Child_ is the constructor of the list items. Used when parsing.

### complex

_complex(acc, tag, items)_

Extends the _acc_ **accessor**, and sets the tagnName of its xml representation to _tag_.
_acc_ will be used as a **complex** object.
_items_ is an Array of keys used when serializing and parsing.

## Methods on OXM Objects

### xml

_obj.xml()_
Returns the node (xmldom), representing the data of _obj_ **oxm_object**.

_obj.xml(node)_
Parses the node (xmldom) and updates the data in _obj_ **oxm_object**.

### js

This helper method makes it possible to recursively convert between **oxm objects** and unwrapped JS values.

_**data**.js()_
Calls **accessor**() and returns it's value.

_**data**.js(value)_
Calls **accessor**(_value_).

_**list**.js()_
Maps **oxm_object**.js on the Array returned from **accessor**(), and returns the new Array.

_**list**.js(array)_
Calls _(new Child()).js(item)_ on each items in _array_, and stores the resulting array.

_**complex**.js()_
Maps the stored Object's items (returned from **accessor**()) with **oxm_object**.js, and returns the new Object.

_**complex**.js(obj)_
Maps _obj_'s items and stores them in **accessor**.

## Usage

  * In browser with browserify
  * In Node

## Example

Shoppig cart

```javascript


var oxm = require("../lib/index.js");
var ko = require("knockout");

// easy date handling
var moment = require("moment");

// pretty printing xml
var pd = require("pretty-data").pd;



// can store a date (mementjs)
var typeDate = function() {
    return ko.computed({
        "read": function() {
            var value = this();
            if (typeof value === "undefined" || value === null) {
                return null;
            } else {
                return value.format("YYYY.MM.DD");
            }
        },
        "write": function(v) {
            if (typeof v === "undefined" || v === null || v === "") {
                this(null);
            } else {
                var parsed = moment(v, "YYYY.MM.DD");

                if (!parsed.isValid()) {
                    throw "Cannot parse date: '" + v + "'";
                }

                this(parsed);
            }
        },
        "owner": ko.observable(null)
    });
};

// can store a double
var typeDouble = function() {
    return ko.computed({
        "read": function() {
            return this();
        },
        "write": function(v) {
            if (typeof v === "undefined" || v === null || v === "") {
                return this(null);
            } else {
                var parsed = parseFloat(v);
                if (isNaN(parsed)) {
                    throw new Error("Cannot parse number: '" + v + "'");
                }

                return this(parsed);
            }
        },
        "owner": ko.observable(null)
    });
};

// can store an integer
var typeInt = function() {
    return ko.computed({
        "read": function() {
            return this();
        },
        "write": function(v) {
            if (typeof v === "undefined" || v === null || v === "") {
                return this(null);
            } else {
                var parsed = parseInt(v, 10);
                if (isNaN(parsed)) {
                    throw new Error("Cannot parse number: '" + v + "'");
                }

                return this(parsed);
            }
        },
        "owner": ko.observable(null)
    });
};


// defining fields:

var Name = function() {
    return oxm.data(ko.observable(null), "name");
};

var Price = function() {
    return oxm.data(typeDouble(), "price");
};

var Product = function() {
    return oxm.complex(ko.observable({
        "name": new Name(),
        "price": new Price()
    }), "product", ["name", "price"]);
};

var Count = function() {
        return oxm.data(typeInt(), "count");
};

var Item = function() {
    return oxm.complex(ko.observable({
        "product": new Product(),
        "count": new Count()
    }), "item", ["product", "count"]);
};

var Items = function() {
    return oxm.list(ko.observableArray([]), "items", Item);
};

var OrderDate = function() {
    return oxm.data(typeDate(), "order-date");
};

var Cart = function() {
    var internal = {};
    var cart = oxm.complex(ko.observable(internal), "cart", ["order-date", "items", "sum"]);

    internal["order-date"] = new OrderDate();
    internal["items"] = new Items();

    // stores nothing, but calculetes the cart sum price on serialization

    internal["sum"] = oxm.data(function() {
        var items = internal["items"].js();

        var s = 0;

        for (var i = 0; i < items.length; i += 1) {
            s += items[i].count * items[i].product.price;
        }

        return s;
    }, "sum");

    return cart;
};

// Create a cart object

var cart1 = new Cart();

// Fill it with data
cart1.js({
    "order-date": "2017.01.21",
    "items": [
        {
            "product": {
                "name": "A fancy car",
                "price": 99999.99
            },
            "count": 2
        },
        {
            "product": {
                "name": "Bread",
                "price": 1.00
            },
            "count": 1
        }
    ]
});

// Create another cart
var cart2 = new Cart();

// Clone the data
cart2.js(cart1.js());

/*
You can duplicate data with the xml methods too:

cart2.xml(cart1.xml()); // serializing/parsing values as nodes (xmldom)
oxm.xml(cart2, oxm.xml(cart1)); // serializing/parsing values as xml string
*/

// Add a new item to the cart
var milk = new Item();

milk.js({"product": {"name": "Milk", "price": 2}, "count": 5});
cart2()["items"]().push(milk);


console.log(pd.xml(oxm.xml(cart1)));

/* output:

<cart>
  <order-date>2017.01.21</order-date>
  <items>
    <item>
      <product>
        <name>A fancy car</name>
        <price>99999.99</price>
      </product>
      <count>2</count>
    </item>
    <item>
      <product>
        <name>Bread</name>
        <price>1</price>
      </product>
      <count>1</count>
    </item>
  </items>
  <sum>200000.98</sum>
    </cart>

*/

console.log(JSON.stringify(cart1.js(), null, "\t"));

/* output:

{
        "order-date": "2017.01.21",
        "items": [
                {
                        "product": {
                                "name": "A fancy car",
                                "price": 99999.99
                        },
                        "count": 2
                },
                {
                        "product": {
                                "name": "Bread",
                                "price": 1
                        },
                        "count": 1
                }
        ],
        "sum": 200000.98
}

*/

console.log(pd.xml(oxm.xml(cart2)));

/* output:

<cart>
  <order-date>2017.01.21</order-date>
  <items>
    <item>
      <product>
        <name>A fancy car</name>
        <price>99999.99</price>
      </product>
      <count>2</count>
    </item>
    <item>
      <product>
        <name>Bread</name>
        <price>1</price>
      </product>
      <count>1</count>
    </item>
    <item>
      <product>
        <name>Milk</name>
        <price>2</price>
      </product>
      <count>5</count>
    </item>
  </items>
  <sum>200010.98</sum>
</cart>

*/

console.log("Cart 1 sum: " + cart1().sum()); // Cart 1 sum : 200000.98
console.log("Cart 2 sum: " + cart2().sum()); // Cart 1 sum : 200010.98

```

---
_Source: https://npm.io/package/oxm · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
