开发者

How do you check for xsi:nil when parsing XML in Javascript?

I haven't done too much XML parsing in the past, I have a page now that works fine in IE but fails in Firefox. The XML document uses xsi:nil="true" for any values that are empty, it looks like the line below

<PlannedDistanceInMeters xsi:nil="true" />

开发者_Go百科I am grabbing needed text using the code below, which works on any nodes that do have text values (workout[i] is a set of nodes I am working through). Also it's external XML so I can't change anthing on the XML side.

workouts[i].getElementsByTagName("PlannedDistanceInMeters")[0].firstChild.data;

For some reason IE completely seems to ignore this when attempting to grab text from "PlannedDistanceInMeters" and parses the document. FF has an error in the console that shows up the moment my code attempts to parse that line and then the code fails.

Error: workouts[i].getElementsByTagName("PlannedDistanceInMeters")[0].firstChild is null

So what is the best way to check for these empty elements?


The error message itself is the solution. If the element has no children, firstChild will be null:

var e = workouts[i].getElementsByTagName("PlannedDistanceInMeters")[0].firstChild;
if (e == null) {
  // no child
} else {
  // access properties of e
}

Alternatively, you can explicitly check if an xsi:nil attribute is present:

var e = workouts[i].getElementsByTagName("PlannedDistanceInMeters")[0];
if (e.hasAttribute('xsi:nil')) {
  ...
} else {
  ...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜