使用javascript的多功能xml属性正则表达式 [英] Versatile xml attribute regex with javascript

查看:90
本文介绍了使用javascript的多功能xml属性正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我有一个xml文档,我对该文档唯一了解的是属性名称。

Basically I have an xml document and the only thing I know about the document is an attribute name.

鉴于该信息,我必须找出该属性名称存在,如果它存在,我需要知道属性值。

Given that information, I have to find out if that attribute name exists, and if it does exist I need to know the attribute value.

例如:

<xmlroot>
  <ping zipcode="94588" appincome = "1750" ssn="987654321" sourceid="XX9999" sourcepw="ioalot">
  <status statuscode="Success" statusdescription="" sessionid="1234" price="12.50"> 
  </status>
</ping>
</xmlroot>

我有名字appincome和sourceid。有什么价值?

I have the names appincome and sourceid. what are the values?

如果文档中有两个appincome属性名称我也需要知道,但我不需要他们的值,只是更多然后存在一个匹配。

Also if there are two appincome attribute names in the document I need to know that too, but I don't need their values, just that more then one match exists.

推荐答案

正则表达式可能不是最好的工具,特别是如果你的JS运行得相当现代支持XPath的浏览器。这个正则表达式应该可行,但如果你没有严格控制文档的内容,请注意误报:

Regular expressions may not be the best tool for this, particularly if your JS is running in reasonably modern browsers with XPath support. This regex should work, but beware of false positives if you don't have tight control over the document's contents:

var match, rx = /\b(appincome|sourceid)\s*=\s*"([^"]*)"/g;

while (match = rx.exec(xml)) {
    // match[1] is the name
    // match[2] is the value

    // this loop executes once for each instance of each attribute
}

或者,试试这个XPath,它不会产生误报:

Alternatively, try this XPath, which won't generate false positives:

var node, nodes = xmldoc.evaluate("//@appincome|//@sourceid", xmldoc, null, XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null);

while (node = nodes.iterateNext()) {
    // node.nodeName is the name
    // node.nodeValue is the value

    // this loop executes once for each instance of each attribute
}

这篇关于使用javascript的多功能xml属性正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆