I will tell you how to do it with JAXB.
First of all, your XML is not very well formed. You have filed instead of field in several places.
Valid XML:
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <data> <keyword name="text123"> <profile num="1"> <url>http://www.a.com</url> <field-1 param="">text</field-1> <field-2 param="">text</field-2> </profile> <profile num="2"> <url>http://www.b.com</url> <field-1 param="">text</field-1> <field-2 param="">text</field-2> </profile> </keyword> <keyword name="textabc123"> <profile num="1"> <url>http://www.1a.com</url> <field-1 param="">text</field-1> <field-2 param="">text</field-2> </profile> <profile num="2"> <url>http://www.1b.com</url> <field-1 param="">text</field-1> <field-2 param="">text</field-2> </profile> </keyword> </data>
Then go to this site and download Trang.
Assuming your XML file is named sample.xml , run it through Trang using java -jar trang.jar sample.xml sample.xsd to get the xsd schema for your xml file.
Now run xjc sample.xsd (xjc is a tool for creating Java classes for an XML schema, complete with the Java 6 SDK).
You will get a list of Java classes:
generated \ Data.java
generated \ Field1.java
generated \ Field2.java
generated \ Keyword.java
generated \ ObjectFactory.java
generated \ Profile.java
Put them in your Java project file and put sample.xml where your program can find it. Now you get the keyword names:
JAXBContext context = JAXBContext.newInstance(Data.class); Data data = (Data)context.createUnmarshaller().unmarshal(new File("sample.xml")); List<Keyword> keywords = data.getKeyword(); for (Keyword keyword : keywords) { System.out.println(keyword.getName()); }
This method may seem a bit confusing at startup, but if your XML structure does not change, I will be better off working with typed Java objects than with the DOM itself.
source share