App下載
首頁javadomJava HTML/XML - 如何將xml字符串轉(zhuǎn)換為列表

Java HTML/XML - 如何將xml字符串轉(zhuǎn)換為列表

我們想知道如何將xml字符串轉(zhuǎn)換為列表。
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

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

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class Main {
  public static void main(String arg[]) throws Exception{
    String xmlRecords = "<root><x>1</x><x>2</x><x>3</x><x>4</x></root>";
    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xmlRecords));

    Document doc = db.parse(is);
    NodeList nodes = doc.getElementsByTagName("x");
    System.out.println(nodes.getLength());
    List<String> valueList = new ArrayList<String>();
    for (int i = 0; i < nodes.getLength(); i++) {
      Element element = (Element) nodes.item(i);
      String name = element.getTextContent();
     // Element line = (Element) name.item(0);
      System.out.println("Name: " + name);
      valueList.add(name);
    }
  }
}