Error parsing XML file in JavaScript
I'm trying to parse a simple XML file but I'm having trouble trying to obtain a value I need. The current error message I'm getting says node is not an object or is null. I'm testing on both I.E. 6, 7, FF 2,3
Here's the XML file:
<bookstore>
<appSettings>
<add key="myKey" value="myTargetValue"/>
</appSettings>
</bookstore>
Here's the script I'm trying to use:
<html>
<head>
<title></title>
</head>
<script type="text/javascript">
if (window.XMLHttpRequest)
{
xhttp = new window.XMLHttpRequest()
}
else
{
xhttp = new ActiveXObject("Microsoft.XMLHTTP")
}
xhttp.open("GET","test.xml",false);
xhttp.send("");
xmlDoc=xhttp.responseXML;
aler开发者_如何学JAVAt(xmlDoc.xml)
var xpath = "/bookstore/appSettings/add[@key='myKey']";
var node = xmlDoc.selectSingleNode(xpath);
alert(node.getAttribute("value"));
</script>
<body>
</body>
</html>
Please advise. Thank you.
I would strongly advise using a library such as jQuery to make your life easier - no more document.getElementById()
-ing! In jQuery you can just do:
$.ajax({
type: 'GET',
url: 'test.xml',
dataType: 'xml',
success: processXml
});
function processXml(xml)
{
xml = $(xml);
var value = xml.find('bookstore appSettings add[key=myKey]').attr('value');
alert(value);
}
Edit: I'm not that familiar with XPath, so I figured I would explain the find()
call in case I misread what you're trying to select from the XML. jQuery uses CSS selector syntax. So, that find()
will select add
nodes that have the key
attribute equal to myKey
, which are descendant elements of appSettings
, which descend from bookstore
elements.
The method for evaluating your Xpath is not correct for firefox.
See https://developer.mozilla.org/en/Introduction_to_using_XPath_in_JavaScript For a good intro to using XPath in firefox.
Also see http://www.w3.org/TR/xpath for XPath details
For your example, you would need
var node = xmlDoc.evaluate("/bookstore/appSettings/add[@key='myKey']", xmlDoc, null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue;
See http://www.w3schools.com/XPath/xpath_examples.asp for How to accomplish this in both IE and firefox
Just to make sure your XML is returning correctly, can you please alter your code:
// ...
xhttp.send("");
xmlDoc=xhttp.responseXML;
alert(xmlDoc.xml)
I suspect you don't get your XML data back from your request.
Before dealing with JavaScript, I would try to open the XML document directly in the browser typing the URL and see if it displays correctly.
精彩评论