cesarbarone / angular-x2js

A simple angular service that wraps x2js lib
Other
20 stars 17 forks source link

how to nest xml #4

Closed cyrfer closed 9 years ago

cyrfer commented 9 years ago

Thanks for providing this project. I'm trying to add more content to a xml node using javascript, but I do not see how to do it.

For example, I already have this:

<g myAttrib="fixed"></g>

But I want to add an arbitrary children, and I do not know what those children will be. They might be:

<circle cx="10" cy="10" r="10" />
<rect x="0" y="0" width="10" height="10"/>

And the result needs to be:

<g myAttrib="fixed">
  <circle cx="10" cy="10" r="10" />
  <rect x="0" y="0" width="10" height="10"/>
</g>

I tried the following, but the conversion from json to xml string was messy.

var innerStr = '<circle cx="10" cy="10" r="10" />
  <rect x="0" y="0" width="10" height="10"/>';

var result = x2js.json2xml_str({
  g: {
    _myAttrib: 'fixed',
    __text: innerStr
  }
});

// only prints "&lt;circle cx=&quot;10&quot; cy=&quot;10&quot; r=&quot;10&quot;&gt;&lt;&#x2F;circle&gt;" instead of the complete xml string
console.log(result);
cyrfer commented 9 years ago

I think I solved this. I needed to do the following:

var top = {};
// set nested content
top.g = x2js.xml_str2json(innerStr);

// add attributes to top.g
top.g._myAttrib = 'fixed'