如何从url解析xml获取属性javascript

时间:2014-11-27 08:50:07

标签: javascript jquery ajax xml parsing

我需要从网址url xml

解析xml
<?xml version="1.0" encoding="UTF-8"?>
<exchangerates>
  <row>
    <exchangerate ccy="RUR" base_ccy="UAH" buy="0.33291" sale="0.33291"/>
  </row>
  <row>
    <exchangerate ccy="EUR" base_ccy="UAH" buy="18.60253" sale="18.60253"/>
  </row>
  <row>
    <exchangerate ccy="USD" base_ccy="UAH" buy="14.97306" sale="14.97306"/>
  </row>
</exchangerates>

我知道使用&#34; 14.97306&#34;转换我的货币

(like mycurrency = 10 )
(like usd = 14.97306 )
(mycurrency * usd = 149.7306)

1 个答案:

答案 0 :(得分:1)

这是Java的基本设置。您需要阅读XPATH查询,并且需要添加异常处理等。但我确信这会让您入门。

    // open the URL
    URL url = ....
    InputStream is = url.openStream();

    // build a document parser
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);
    DocumentBuilder builder = domFactory.newDocumentBuilder();

    // parse the document from the URL
    Document d = builder.parse(is);

    // set up XPATH to examine/query the XML
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();

    // use XPATH query to find the required information
    String sale = xpath.evaluate("/exchangerates/row[@ccy='USD']/@sale", d);

    System.out.println("USD sale is "+sale);