问题
I want to read all link and title at the same time to array list?
<rootNode>
<image>
<link>http://imagelink/</link>
<title>This is the title</title>
</image>
<movie>
<link>http://movielink/</link>
<title>This is the title</title>
</movie>
</rootNode>
Code below works fine but, where there are different child nodes it can make code too big.
I don't want multiple for, I want something that looks clean!
ArrayList XTimeStamp = new ArrayList();
Node libraryTagNode, libraryDataNode;
Element libraryTagElement, libraryDataElement;
NodeList libraryTagList,libraryDataList;
try {
File file = new File("computer.txt");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();
NodeList imageLst = doc.getElementsByTagName("image");
NodeList movieLst = doc.getElementsByTagName("movie");
for (int s = 0; s < imageLst.getLength(); s++) {
libraryTagNode=bookLst.item(s);
if (libraryTagNode.getNodeType() == Node.ELEMENT_NODE) {
libraryTagElement = (Element) libraryTagNode;
libraryTagList = libraryTagElement.getElementsByTagName("link");
libraryDataElement = (Element) libraryTagList.item(0);
libraryDataList = libraryDataElement.getChildNodes();
String timeStampX=libraryDataList.item(0).getNodeValue();
libraryTagList = libraryTagElement.getElementsByTagName("title");
libraryDataElement = (Element) libraryTagList.item(0);
libraryDataList = libraryDataElement.getChildNodes();
String timeStampY=libraryDataList.item(0).getNodeValue();
XTimeStamp.add(timeStampX+" "+timeStampY);
}
}
for (int s = 0; s < movieLst.getLength(); s++) {
libraryTagNode=bookLst.item(s);
if (libraryTagNode.getNodeType() == Node.ELEMENT_NODE) {
libraryTagElement = (Element) libraryTagNode;
libraryTagList = libraryTagElement.getElementsByTagName("link");
libraryDataElement = (Element) libraryTagList.item(0);
libraryDataList = libraryDataElement.getChildNodes();
String timeStampX=libraryDataList.item(0).getNodeValue();
libraryTagList = libraryTagElement.getElementsByTagName("title");
libraryDataElement = (Element) libraryTagList.item(0);
libraryDataList = libraryDataElement.getChildNodes();
String timeStampY=libraryDataList.item(0).getNodeValue();
XTimeStamp.add(timeStampX+" "+timeStampY);
}
}
回答1:
I'm guessing you want to roll the two loops into one somehow as this is certainly a cumbersome way to do it as it is now.
The answer is to use XPath. I would suggest you search for <title> elements whose parent holds a <link> element.
回答2:
Use XPATH - see http://www.ibm.com/developerworks/library/x-javaxpathapi/index.html
回答3:
Not 100% sure on what your asking but if you want to get all the link nodes in a NodeList and all the title nodes in a different nodelist you could try XPath using "//link" and "//title" as your XPath expression
来源:https://stackoverflow.com/questions/8578455/java-all-child-element-reading-in-xml