Leonidas-from-XIV / node-xml2js

XML to JavaScript object converter.
MIT License
4.84k stars 599 forks source link

Need a way to ignore xmlns attribute #537

Open bdsanfelippo opened 4 years ago

bdsanfelippo commented 4 years ago

The xml I am parsing has the xmlns attribute in many locations. For example:

<sports xmlns="...">
    <basketball xmlns="...">data</basketball>
    <soccer xmlns="...">data</soccer>
</sports>

Is there a way to exclude an attribute? Or to just exclude the xmlns attribute wherever it may appear? I could always iterate over the entire object when I get it parsed and manually delete but it seems there should be a better way.

I tried the processors but they seem to only change a value or name, not remove one altogether.

moraleslevi commented 4 years ago

I was able to solve this issue by returning undefined when attribute name was xmlns in the attrValueProcessors.

bdsanfelippo commented 4 years ago

Thanks for the reply @moraleslevi.

If I understand you correctly, I would do something like this:

function filterOutAttributes(value, name) {
    if (name === "xmlns") {
        return undefined;
    }
}

const customParser = new xml2js.Parser({
    attrValueProcessors: [filterOutAttributes]
});

When I run that, I still see the xmlns object in the json object. It is just set to undefined. That is I guess better but still not what I'm looking for.

moraleslevi commented 4 years ago

That is odd. I am doing essentially what you posted above, but I do not see the xmlns in the json output. Here is my full configuration:

function cleanOutput (value, name) {
  if (name === 'xmlns:xsi') {
    return undefined
  }

  // other custom manipulations

  return value
}

const Parser = new xml2js.Parser({
  normalizeTags: true,
  mergeAttrs: true,
  explicitRoot: false,
  explicitArray: false,
  attrValueProcessors: [cleanOutput],
  valueProcessors: [cleanOutput]
})
bdsanfelippo commented 4 years ago

You aren't by chance using JSON.stringify to view the data are you? I know that will hide key/values where the value is undefined. I'll try to create a standalone xml example for this.

moraleslevi commented 4 years ago

Ah yes, I am. The output is being sent to JSON.stringify to write json to the file system. That is probably where the discrepancy lies.