在Ajax 应用程序中实现数据之间交换

作者:凯旋网络来源:凯旋网络
mplexType>

< /xsd:schema>
 

 DataModel 类的 parsePortfolioDoc() 方法使用 XMLUtil 验证和分析 xml 参数,并返回一个 DOM 文档:

private static final String SCHEMA_NAME
= "/ajaxapp/model/portfolio.xsd";
private static DocumentBuilderFactory parserFactory;
   
private static Document parsePortfolioDoc(String xml)
throws IOException, SAXException,
ParserConfigurationException {
synchronized (DataModel.class) {
if (parserFactory == null)
parserFactory = XMLUtil.newParserFactory(SCHEMA_NAME);
    }
DocumentBuilder parser = XMLUtil.newParser(parserFactory);
InputSource in = new InputSource(new StringReader(xml));
return parser.parse(in);
}


  现在,您拥有了一个 DOM 树,接下来要获取形成 DOM 节点所需的数据。

  提取所需信息。您可以使用 DOM API 或查询语言(如 XQuery 或 XPath)来浏览 DOM 树。Java 为 XPath 提供了标准的 API,后面会用到。XMLUtil 类创建一个具有 newXPath() 方法的 XPathFactory:

import javax.xml.xpath.*;
...
protected static XPathFactory xpathFactory;
static {
xpathFactory = XPathFactory.newInstance();
}
   
public static XPath newXPath() {
return xpathFactory.newXPath();
}


  以下方法在给定的上下文中求解 XPath 表达式,返回结果值:

import javax.xml.xpath.*;
import org.w3c.dom.*;
...
public static String evalToString(String expression,
Object context) throws XPathExpressionException {
return (String) newXPath().evaluate(expression, context,
XPathConstants.STRING);
}
   
public static boolean evalToBoolean(String expression,
Object context) throws XPathExpressionException {
return ((Boolean) newXPath().evaluate(expression, context,
XPathConstants.BOOLEAN)).booleanValue();
}
   
public static double evalToNumber(String expression,
Object context) throws XPathExpressionException {
return ((Double) newXPath().evaluate(expression, context,
XPathConstants.NUMBER)).doubleValue();
}
   
public static Node evalToNode(String expression,
Object context) throws XPathExpressionException {
return (Node) newXPath().evaluate(expression, context,
XPathConstants.NODE);
}
   
public static NodeList evalToNodeList(String expression,
Object context) throws XPathExpressionException {
return (NodeList) newXPath().evaluate(expression, context,
XPathConstants.NODESET);
}

 DataModel 的 setData() 方法使用 XPath 求解方法从组合 XML 文档提取信息:

public synchronized void setData(String xml)
throws IOException, SAXException,
ParserConfigurationException,
XPathExpressionException {
try{
ArrayList stockList
= new ArrayList();
Document doc = parsePortfolioDoc(xml);
NodeList nodeList = XMLUtil.evalToNodeList(
"/portfolio/stock", doc);
for (int i = 0; i <  nodeList.getLength(); i++) {
Node node = nodeList.item(i);
StockBean stock = new StockBean();
stock.setSymbol(
XMLUtil.evalToString("@symbol", node));
stock.setShares(
(int) XMLUtil.evalToNumber("@shares", node));
stock.setPaidPrice(
XMLUtil.evalToNumber("@paidPrice", node));
stockList.add(stock);
        }
this.stockList = stockList;
} catch (Excepti

  • 广告推荐