Here's the idea of the xml file:
<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>
What I'm trying to figure out how to do is, for example, on August 30, put items 1 and 2 in the aug30 tags into a JList, and on August 31, put items 1, 2 and 3 from the aug31 tags into that same JList.
Here you go. This finds only the sections based on the date. I haven't shown the adding to JList, as thats easy. Just change the print statement which prints ADD and you are good to go.
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();
}
The imports are:
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.