App下載
首頁(yè)javadomJava HTML/XML - 如何使用XML鍵名訪問(wèn)值

Java HTML/XML - 如何使用XML鍵名訪問(wèn)值

我們想知道如何使用XML鍵名訪問(wèn)值。
import java.io.FileInputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class Main {
  public static void main(String args[]) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = dbf.newDocumentBuilder();
    Document doc = docBuilder.parse(new FileInputStream("data.xml"));
    Element root = doc.getDocumentElement();
    org.w3c.dom.NodeList nodeList = root.getElementsByTagName("key");
    for (int i = 0; i < nodeList.getLength(); i++) {
      System.out.print(((Node) nodeList.item(i)).getAttributes().getNamedItem(
          "keyname"));
      System.out.println("\tvalue: "
          + ((Node) nodeList.item(i)).getTextContent());
    }

  }
}