Using xml2js to parse an XML file, I need to retrieve the value of an attribute which contains a hyphen in its name
<item cdr-id="1234">
<name>some text</name>
</item>
At the point where I'm trying to retrieve cdr-id
, I already have a variable item
which points to the item element. I've verified it's pointing to the proper node with
console.log(item.name);
and that returns the expected value some text
. But when I try
console.log(item.$.cdr-id);
I get the completely reasonable error ReferenceError: id is not defined
(I'd have been more surprised if id
wasn't treated as a separate token).
Likewise,
console.log(item.$."cdr-id");
gets the message SyntaxError: Unexpected string
.
Throwing JSON.stringify around it
console.log( JSON.stringify(item.$));
reveals the original attribute name: {"cdr-id":"CDR0000040222"}
Not having hyphens in the name in the first place just kicks the problem down the road a bit. Failing that, it looks like providing a custom attribute name processor is the way to go, but that smacks of being "too clever" with potential for confusion if anyone ever has to update this code.
Is there a better way to do this?
喜欢
console.log(item.$["cdr-id"]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.