[英]xml2js, attribute name contains a hyphen
Using xml2js to parse an XML file, I need to retrieve the value of an attribute which contains a hyphen in its name 使用xml2js解析XML文件时,我需要检索名称中包含连字符的属性的值
<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. 在我试图检索
cdr-id
,我已经有一个指向item元素的变量item
。 I've verified it's pointing to the proper node with 我已经验证它指向正确的节点
console.log(item.name);
and that returns the expected value some text
. 然后返回期望值
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). 我得到了完全合理的错误
ReferenceError: id is not defined
(如果未将id
视为单独的标记,我会感到更加惊讶)。
Likewise, 同样,
console.log(item.$."cdr-id");
gets the message SyntaxError: Unexpected string
. 获取消息
SyntaxError: Unexpected string
。
Throwing JSON.stringify around it 抛出JSON.stringify
console.log( JSON.stringify(item.$));
reveals the original attribute name: {"cdr-id":"CDR0000040222"}
显示原始属性名称:
{"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"]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.