簡體   English   中英

使用Java,我將如何從網站讀取xml文件,然后將xml文件中的數據放入JList中?

[英]Using java, how would I read an xml file from a website then put the data from the xml file in a JList?

這是xml文件的概念:

<date>
<aug30>
    <item1>This is an item for August 30</item1>
    <item2>This is another item for August 30</item2>
</aug30>
<aug31>
    <item1>This is an item for August 31</item1>
    <item2>This is another item for August 31</item2>
    <item3>This is a 3rd item for August 31</item3>
</aug31>
</date>

我要弄清楚的方法是,例如,在8月30日,將aug30標記中的項目1和2放入JList中,並在8月31日,將aug31標記中的項目1、2和3放入JList中。相同的JList。

干得好。 這僅根據日期查找部分。 我還沒有顯示添加到JList的過程,那很容易。 只需更改打印ADD的打印語句,就可以了。

    String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
    "<date>\n" +
    "<aug30>\n" +
    "    <item1>This is an item for August 30</item1>\n" +
    "    <item2>This is another item for August 30</item2>\n" +
    "</aug30>\n" +
    "<aug31>\n" +
    "    <item1>This is an item for August 31</item1>\n" +
    "    <item2>This is another item for August 31</item2>\n" +
    "    <item3>This is a 3rd item for August 31</item3>\n" +
    "</aug31>\n" +
    "</date>\n";

    SimpleDateFormat df = new SimpleDateFormat("MMMd");
    String date = df.format(new Date()).toLowerCase();

    try {
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = builder.parse(new InputSource(new StringReader(xml)));

        DocumentTraversal traversal = (DocumentTraversal) doc;

        NodeIterator iterator = traversal.createNodeIterator(
          doc.getDocumentElement(), NodeFilter.SHOW_ELEMENT, null, true);

        for (Node n = iterator.nextNode(); n != null; n = iterator.nextNode()) {
            String tagname = ((Element) n).getTagName();
            //System.out.println("Compare TAG: '" + tagname + "' with '" + date + "'");
            if(tagname.equals(date)) {
                n = iterator.nextNode();
                tagname = ((Element) n).getTagName();
                while(tagname.startsWith("item") && n != null) {
                    System.out.println("ADD: " + ((Element)n).getTextContent());
                    n = iterator.nextNode();
                    if(n != null) {
                        tagname = ((Element) n).getTagName();
                    } 
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

進口是:

import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.Date;

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;
import org.w3c.dom.traversal.DocumentTraversal;
import org.w3c.dom.traversal.NodeFilter;
import org.w3c.dom.traversal.NodeIterator;
import org.xml.sax.InputSource;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM