xml-js icon indicating copy to clipboard operation
xml-js copied to clipboard

Option to extract attributes without 'attr' key, on element level

Open 11111000000 opened this issue 5 years ago • 8 comments

i.e.

<SomeThing SomeAttr="VALUE">CONTENT</SomeThing>

=>

{
  SomeThing : {
    SomeAttr: "VALUE"
    _text: "CONTENT"
  }
}

instead of

{
  SomeThing : {
    _attrs: {
     SomeAttr: "VALUE"
   },
    _text: "CONTENT"
  }
}

or how to implement this effectively?

11111000000 avatar Jan 24 '20 10:01 11111000000

maybe allow transformations like postPlaceFn: (key, ctx, default) => (key == '_attributes') ? ctx : ctx[key] or similar?

11111000000 avatar Jan 24 '20 18:01 11111000000

Hi, is this implemented in the actual versión? attrsAsProps: true

sebafra avatar May 20 '20 17:05 sebafra

Any updates on this?

dsisk112 avatar Jun 29 '21 20:06 dsisk112

I created a quick and dirty PR to do this https://github.com/nashwaan/xml-js/pull/195

1mike12 avatar Nov 23 '22 22:11 1mike12

Would be great to see this implemented

plckr avatar Mar 06 '23 22:03 plckr

I did some tests, and this seems to work 😮

xml2js(xml, {
  compact: true,
  alwaysArray: true,
  attributesFn: (attributes, parent) => {
    Object.assign(parent, attributes);
    return undefined;
  }
})

EDIT: Hmmm, maybe there's no data if the tag has no children 😕

plckr avatar Mar 06 '23 22:03 plckr

<SomeThing SomeAttr="VALUE">CONTENT</SomeThing>

may be converted to json

{
  "SomeThing": {
    "-SomeAttr": "VALUE",
    "#text": "CONTENT"
  },
  "#omit-xml-declaration": "yes"
}

javadev avatar Apr 28 '23 22:04 javadev

Removing the attributes parent node would be useful for size reduction. In my case a json file goes:

  • Before: 766 lines / 14KB
  • After: 532 lines / 10KB

kmturley avatar Jan 22 '24 04:01 kmturley