Remplir un tableau avec les attributs d'un fichier XML
Je veux remplir un tableau par la première attribut de chaque élément
par exemple j'ai un document XML comme suit:
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
<root>
<element name="time" idref="id1">
<sub-elt1>val1</sub-elt1>
<sub-elt2>val2</sub-elt2>
<sub-elt3>val3</sub-elt3>
</element>
<element name="Place" idref="id2">
<sub-elt1>val1</sub-elt1>
<sub-elt2>val2</sub-elt2>
<sub-elt3>val3</sub-elt3>
</element>
</root> |
je veux parcourir ce document pour avoir un tableau qui contient ensemble des noms des éléments : "time", "Place"
voici mon code qui ne m'affiche rien.
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
|
package Exampl;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class ParseXML5 {
public static void main(String[] args) {
try {
File file = new File("E:\\expXML.xml");
DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document doc = dBuilder.parse(file);
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
if (doc.hasChildNodes()) {
printNote(doc.getChildNodes());
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
private static void printNote(NodeList nodeList) {
String[] st= new String[10];
int k = 0;
for (int j = 0; j < nodeList.getLength(); j++) {
Node tempNode = nodeList.item(j);
// make sure it's element node.
if (tempNode.getNodeType() == Node.ELEMENT_NODE) {
if (tempNode.hasAttributes()) {
NamedNodeMap nodeMap = tempNode.getAttributes();
for (int i = 0; i < nodeMap.getLength(); i++) {
Node node = nodeMap.item(i);
System.out.println("attr name : " + node.getNodeName());
System.out.println("attr value : " + node.getNodeValue());
st[k]= node.getNodeName();
k++;
}
}
}
}
}
} |