How to count children as xml element?
I know this has been asked before, but I'm a little lost here.
I have an element from which I am writing typeof:
typeof msg['PID']['PID.13'] // outputs "xml"
So, following this answer , I have logged children.length
from which I expect it to be a number:
typeof msg['PID']['PID.13'].children.length // also outputs "xml"
But the type is children.length
also xml
. How can it be?
This Javascript is hidden in the system (Mirth) where logging is an issue (at least I still haven't figured out how it works), so it's hard for me to debug this.
Does anyone know how I can count the number of items? All advice is appreciated!
[EDIT] As suggested, I also tried the output msg['PID']['PID.13'].children.length
, but it seems blank.
source to share
The first thing that seems pretty strange to me is typeof msg['PID']['PID.13'] // 'xml'
. So, in case you get some xml from the server, you can parse it like this:
var parser = new DOMParser(),
doc = parser.parser.parseFromString(xml, 'text/xml'); //xml is a xml string
typeof doc // 'object'
Than to count occurrences of some elements / children you can use xpath:
var count = doc.evaluate('count(//someelement)', doc.documentElement, null, XPathResult.NUMBER_TYPE, null).numberValue;
You can even run:
doc.querySelectorAll('someelement').length
and those methods from comments will work too:
doc.documentElement.children.length
So, I think that the object xml
you have in this object is not real XMLDocument
, so I believe that these properties like msg['PID']['PID.13'].children.length
"are empty.
UPDATE
As @Nick Rupley's answer pointed out, you can deal with an E4X instance and as described here in the Legacy Content Archive , it is deprecated in firefox and does not appear at all on caniuse.com . Therefore, if your code works in a browser, you need to change it to one of the options mentioned above. Otherwise, you can find usage documentation on the first linked resource on mdn.
source to share
So msg['PID']['PID.13']
- xml. Can you post it here as text? If this xml was something like <children><length><value>5</value></length></children>
, then it msg['PID']['PID.13'].children
could possibly be interpreted by js as if it were msg['PID']['PID.13']['children']
, which is an identical js expression. Likewise, depending on the type of the object, it might return an empty xml node for all invalid nodes, i.e.:
typeof msg['PID']['PID.13'].children.a.b.c.d.length
will return xml as well.
source to share