我希望读取XML文件中的数据并将其存储在jQuery中的数组/其他数据结构中。
这是我的XML数据:
<dependencieList>
<dependencies>
<pluginname>OpenJDK Runtime Environment</pluginname>
<version>1.7.0_65</version>
<description>Open JDK Runtime Environment</description>
</dependencies>
<dependencies>
<pluginname>Adobe Flash Player</pluginname>
<version>17.0 r0</version>
<description>Shockwave Flash Player</description>
</dependencies>
</dependencieList>
我希望XML数据像集合一样存储,就像我们在c编程中那样,我如何在jQuery中实现它?
答案 0 :(得分:0)
试试这个
function xmlToJson(xml) {
// Create the return object
var obj = {};
if (xml.nodeType == 1) { // element
// do attributes
if (xml.attributes.length > 0) {
obj["@attributes"] = {};
for (var j = 0; j < xml.attributes.length; j++) {
var attribute = xml.attributes.item(j);
obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
}
}
} else if (xml.nodeType == 3) { // text
obj = xml.nodeValue;
}
// do children
if (xml.hasChildNodes()) {
for(var i = 0; i < xml.childNodes.length; i++) {
var item = xml.childNodes.item(i);
var nodeName = item.nodeName;
if (typeof(obj[nodeName]) == "undefined") {
obj[nodeName] = xmlToJson(item);
} else {
if (typeof(obj[nodeName].push) == "undefined") {
var old = obj[nodeName];
obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(xmlToJson(item));
}
}
}
return obj;
}
答案 1 :(得分:0)
对你的数据必须有一些合理的假设,否则你什么也得不到
例如,我假设每个节点可能包含以下之一:
- 文字,没有其他内容
- 子节点,全部相等(如<dependencies>
)
- 子节点,全部不同(如<pluginname>
等)
我做了
<script type="text/my-data" id="datasrc">
<dependencieList>
... etc ... your data here
</dependencieList>
</script>
<script>
var src = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" +
$('#datasrc').html(),
result = {};
try {
var $x = $($.parseXML (src)); // rely on jQuery "universal" parsing
parseNode ($x.children().first(), result);
} catch (e) {
}
$('#result').text (JSON.stringify (result, null, 2));
function parseNode ($node, obj) {
var name = $node[0].nodeName,
val = '';
if ($node.children().length) {
val = {};
$node.children().each (function () {
parseNode ($(this), val);
});
} else {
val = $node.text();
}
if (!obj[name]) {
obj[name] = val;
} else if ($.isArray (obj[name])) {
(obj[name]).push (val);
} else {
obj[name] = [obj[name], val];
}
}
</script>
并获得结果
{
"dependencieList": {
"dependencies": [
{
"pluginname": "OpenJDK Runtime Environment",
"version": "1.7.0_65",
"description": "Open JDK Runtime Environment"
},
{
"pluginname": "Adobe Flash Player",
"version": "17.0 r0",
"description": "Shockwave Flash Player"
}
]
}
}
jsFiddle是here