How can I test for XML using jQuery?
如何使用jQuery测试XML ?
I have a bookmarklet that needs to know whether the current page is XML. How can I check for this?
我有一个bookmarklet,它需要知道当前页面是否为XML。我怎么检查?
I imagine I will pass in the document and check for the following:
我想我会把文件传给你,检查一下:
<?xml version="1.0" encoding="UTF-8"?>
But not sure.
但不确定。
1 个解决方案
#1
7
Not sure if you want to load the page again, but you could run it through jQuery.parseXML()
, which will throw an exception for invalid XML, so you could just try to parse the page and if no exception is thrown then it is (valid) XML.
不确定是否要再次加载页面,但是可以通过jQuery.parseXML()运行它,它会对无效的XML抛出异常,因此可以尝试解析页面,如果没有抛出异常,那么它就是(有效的)XML。
For example:
例如:
var xml = "<rss version='2.0'><brokenxml></rss>";
try {
xmlDoc = $.parseXML(xml);
} catch (err) {
// was not XML
}
#1
7
Not sure if you want to load the page again, but you could run it through jQuery.parseXML()
, which will throw an exception for invalid XML, so you could just try to parse the page and if no exception is thrown then it is (valid) XML.
不确定是否要再次加载页面,但是可以通过jQuery.parseXML()运行它,它会对无效的XML抛出异常,因此可以尝试解析页面,如果没有抛出异常,那么它就是(有效的)XML。
For example:
例如:
var xml = "<rss version='2.0'><brokenxml></rss>";
try {
xmlDoc = $.parseXML(xml);
} catch (err) {
// was not XML
}