Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/jonathanconway/xmltodynamic

Converts an XML document into a dynamic object
https://github.com/jonathanconway/xmltodynamic

Last synced: about 12 hours ago
JSON representation

Converts an XML document into a dynamic object

Awesome Lists containing this project

README

        

# XmlToDynamic

XmlToDynamic converts your XML object into a hierarchy of nested objects, so you can get at values and attributes more easily.

Instead of this:

xelement.Element(XName.Get("contact")).Attribute(XName.Get("firstName")).Value

You can type this:

xelement.contact["firstName"]

The object returned is also dynamic, so you can add new properties on-the-fly.

## Usage

To dynamize your XML, simply generate an XElement of it, then call `ToDynamic()` on it.

var xmlString = @"";
var dynamicXml = XElement.Parse(xmlString).ToDynamic();

### Values

The elements get converted to properties, and their values can be accessed through the `Value` property.

//
//
//
// Jonathan
//
//
//
var firstPersonsName = dynamicXml.contacts[0].name.Value;
// firstPersonsName will be 'Jonathan'

### Attributes

Attributes can be accessed through 'index' syntax, as shown below.

//
//
//
// Jonathan
//
//
//
var firstPersonsId = dynamicXml.contacts[0]["id"];
// firstPersonsId will be '1'

### Repeated elements

Whenever repeated elements are encountered, they're put into a container which is named after the element names pluralized.

//
//
//
//
//
var darkGreenLightness = dynamicXml.greens[0]["lightness"];
var lightGreenLightness = dynamicXml.greens[1]["lightness"];
// darkGreenLightness will be '1'
// lightGreenLightness will be '10'