0

Searching a good way to split an XML path into an array. I have the feeling my solution is not as reliable as i want.

What I have: <product><containeditem><productidentifier>

What I want to get is an array like: [product, containeditem, productidentifier]

My Code:

function GetPathArray(path) {
  if (path != null) {
    path = path.substring(0, path.length - 1);
    path = path.substring(1);

    var pathArray = [{}];

    pathArray = path.split("><");

    return pathArray;
  }
  else {
    return null;
  }
}
  • Do you have full/valid XML? Or just a very simple structure such as the one in your question? If it's just a simple fragment (e.g. no closing tags, no content, no attributes - just opening tags), then your approach is probably fine. But as soon as you have anything even slightly more complex, I would recommend you use an XML parser. For example, see [Parse XML using JavaScript](https://stackoverflow.com/questions/17604071/parse-xml-using-javascript) and similar questions. – andrewJames Jun 11 '21 at 12:13
  • For a broader discussion, see [this](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags). – andrewJames Jun 11 '21 at 12:13

2 Answers2

1

To ensure you return an array, not a string, you can use this for the simple case in your question:

var path = '<product><containeditem><productidentifier>';

console.log( getPathArray(path) );

function getPathArray(path){
  return path.slice(1, -1).split('><');
}

The slice function discards the first and last characters (the opening and closing < and >).

Then the split is all you need - as that returns an array.

For more complex strings, this will almost certainly not be sufficient.

andrewJames
  • 19,570
  • 8
  • 19
  • 51
  • After testing a lot, i think my code was working fine but, your way is just more clean and easier to read. Thank you – Malte K.oder Jun 12 '21 at 17:12
0

Answer

As @andrewjames said, the solution depends on how the path looks like. If it is like your example, you can get the solution with basics string methods of JavaScript

Code

function getPathArray(path){
  path = path.split('><').join(', ')
  path = path.replace('<','[')
  path = path.replace('>',']')
  return path
}

References

fullfine
  • 1,371
  • 1
  • 4
  • 11