App下載
首頁javaxpathJava HTML/XML - 如何使用xml表達式和數(shù)據(jù)的xml模式和鍵值對生成xml...

Java HTML/XML - 如何使用xml表達式和數(shù)據(jù)的xml模式和鍵值對生成xml...

我們想知道如何使用xml表達式和數(shù)據(jù)的xml模式和鍵值對生成xml。...
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
  public static void main(String[] args) throws Exception {
    List<String> names = new ArrayList<>();
    URL oracle = new URL("http://weather.yahooapis.com/forecastrss?w=2502265");
    InputStream is = oracle.openStream();
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document doc = builder.parse(is);
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    XPathExpression expr = xpath.compile("http://*:*/@*");
    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    NodeList nl = (NodeList) result;
    for (int i = 0; i < nl.getLength(); i++) {
      names.add(nl.item(i).getNodeName());
      Node node = nl.item(i);
      String path = "." + node.getNodeName() + " = " + node.getNodeValue();
      node = ((Attr) node).getOwnerElement();
      while (node != null) {
        path = node.getNodeName() + '/' + path;
        node = node.getParentNode();
      }
      System.out.println(path);
    }
  }
}