有没有什么好方法可以使用Javascript解析OpenSearch XML?

时间:2012-06-14 08:19:13

标签: javascript

我想解析OpenSearch XML以获取搜索网址,例如“http://stackoverflow.com/search?q={searchTerms}”

XML就像这样:

<?xml version="1.0" encoding="UTF-8" ?>

<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" xmlns:moz="http://www.mozilla.org/2006/browser/search/">
      <ShortName>Stack Overflow</ShortName>
      <Description>Search Stack Overflow: Q&amp;A for professional and enthusiast programmers</Description>
      <InputEncoding>UTF-8</InputEncoding>
      <Image width="16" height="16" type="image/x-icon">http://sstatic.net/stackoverflow/img/favicon.ico</Image>
      <Url type="text/html" method="get" template="http://stackoverflow.com/search?q={searchTerms}"></Url>
</OpenSearchDescription>

2 个答案:

答案 0 :(得分:0)

var domParser = new DOMParser,
    dom = domParser.parseFromString(xml, "application/xml");

console.log( dom.getElementsByTagName("Url")[0].getAttribute("template"));
//"http://stackoverflow.com/search?q={searchTerms}"

答案 1 :(得分:0)

XmlHttpRequest完成工作?我很确定你没有把XML作为字符串。

var dom = xhr.responseXML;
var url = dom.documentElement.querySelector("Url[template]"); // DOM lvl 3!
if (url)
    return url.getAttribute("template");