日期:2014-04-09  浏览次数:20994 次

 以前做了java对xml文件的访问.后来听我的一个同事(技术很牛的哈)说:用javaScript 访问更方便简单.于是今天就回家找材料测试了下.确实很方便.欢迎大家共享!我把我找的测试代码贴出来.也是从别人那里抄过来的.还是改了几处错误哈.当前会有更多的这方面的材料哈!谢谢你的关注!原代码请点击阅读全文.

1.order.xml

<?xml version="1.0"?>
<Order>
<Account>9900234</Account>
<Item id="1">
<SKU>1234</SKU>
<PricePer>5.95</PricePer>
<Quantity>100</Quantity>
<Subtotal>595.00</Subtotal>
<Description>Super Widget Clamp</Description>
</Item>
<Item id="2">
<SKU>6234</SKU>
<PricePer>22.00</PricePer>
<Quantity>10</Quantity>
<Subtotal>220.00</Subtotal>
<Description>Mighty Foobar Flange</Description>
</Item>
<Item id="3">
<SKU>9982</SKU>
<PricePer>2.50</PricePer>
<Quantity>1000</Quantity>
<Subtotal>2500.00</Subtotal>
<Description>Deluxe Doohickie</Description>
</Item>
<Item id="4">
<SKU>3256</SKU>
<PricePer>389.00</PricePer>
<Quantity>1</Quantity>
<Subtotal>389.00</Subtotal>
<Description>Muckalucket Bucket</Description>
</Item>
<NumberItems>1111</NumberItems>
<Total>3704.00</Total>
<OrderDate>07/07/2002</OrderDate>
<OrderNumber>8876</OrderNumber>
</Order>

2: order.html

<html>
<head>
<script language="JavaScript">
<!--
var i = -1;

var orderDoc = new ActiveXObject("MSXML2.DOMDocument.3.0");
orderDoc.load("order.xml");
var items = orderDoc.selectNodes("/Order/Item");

function getNode(doc, xpath) {
var retval = "";
var value = doc.selectSingleNode(xpath);
if (value) retval = value.text;
return retval;
}

function getDataNext() {
i++;
if (i > items.length - 1) i = 0;

document.forms[0].SKU.value = getNode(orderDoc, "/Order/Item[" + i + "]/SKU");
document.forms[0].Price.value = getNode(orderDoc, "/Order/Item[" + i + "]/PricePer");
document.forms[0].Quantity.value = getNode(orderDoc, "/Order/Item[" + i + "]/Quantity");
document.forms[0].Total.value = getNode(orderDoc,"/Order/Item[" + i + "]/Subtotal");
document.forms[0].Description.value = getNode(orderDoc, "/Order/Item[" + i + "]/Description");
}

function getDataPrev() {
i--;
if (i < 0) i = items.length - 1;

document.forms[0].SKU.value = getNode(orderDoc, "/Order/Item[" + i + "]/SKU");
document.forms[0].Price.value = getNode(orderDoc,"/Order/Item[" + i + "]/PricePer");
document.forms[0].Quantity.value = getNode(orderDoc, "/Order/Item[" + i + "]/Quantity");
document.forms[0].Total.value = getNode(orderDoc,"/Order/Item["+ i + "]/Subtotal");
document.forms[0].Description.value = getNode(orderDoc, "/Order/Item[" + i + "]/Description");
}

-->
</script>
</head>
<body >
<h2>XML Order Database</h2>
<form>
<table border="0">
<tr><td>SKU</td><td><input type="text" name="SKU"></td></tr>
<tr><td>Price</td><td><input type="text" name="Price"></td></tr>
<tr><td>Quantity</td><td><input type="text"
name="Quantity"></td></tr>
<tr><td>Total</td><td><input type="text" name="Total"></td></tr>
<tr><t