Created
January 4, 2015 07:41
-
-
Save aVolpe/2ad74af81bf002193dab to your computer and use it in GitHub Desktop.
Answers to the Question Q27758304 of StackOverflow
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package py.com.volpe.stack; | |
import java.io.File; | |
import java.util.ArrayList; | |
import java.util.Arrays; | |
import java.util.List; | |
import javax.xml.bind.JAXBContext; | |
import javax.xml.bind.Unmarshaller; | |
import javax.xml.bind.annotation.XmlAccessType; | |
import javax.xml.bind.annotation.XmlAccessorType; | |
import javax.xml.bind.annotation.XmlAttribute; | |
import javax.xml.bind.annotation.XmlElement; | |
import javax.xml.bind.annotation.XmlRootElement; | |
import javax.xml.bind.annotation.XmlValue; | |
import org.junit.Test; | |
public class Q27758304 { | |
@Test | |
public void testName() throws Exception { | |
String f = getClass().getResource(getClass().getSimpleName() + ".xml") | |
.getPath(); | |
JAXBContext context = JAXBContext.newInstance(GTSResponse.class); | |
Unmarshaller unma = context.createUnmarshaller(); | |
// here you can pass a inputStream instead of a new File | |
GTSResponse response = (GTSResponse) unma.unmarshal(new File(f)); | |
List<String> result = new ArrayList<String>(); | |
for (Record r : response.records) { | |
System.out.println("Start record"); | |
for (Field fi : r.fields) { | |
System.out.println(fi.name + ":" + fi.data + "(Primary: " | |
+ fi.primaryKey + ")"); | |
if (fi.name.equals("deviceID") || fi.name.equals("description")) | |
result.add(fi.data); | |
} | |
} | |
// The array this print is exactly as you want | |
System.out.println(Arrays.toString(result.toArray())); | |
} | |
@XmlRootElement(name = "GTSResponse") | |
@XmlAccessorType(XmlAccessType.FIELD) | |
public static class GTSResponse { | |
@XmlElement(name = "Record") | |
List<Record> records; | |
} | |
@XmlRootElement(name = "Record") | |
@XmlAccessorType(XmlAccessType.FIELD) | |
public static class Record { | |
@XmlElement(name = "Field") | |
List<Field> fields; | |
} | |
@XmlRootElement(name = "Field") | |
@XmlAccessorType(XmlAccessType.FIELD) | |
public static class Field { | |
@XmlAttribute(name = "name") | |
String name; | |
@XmlAttribute(name = "primaryKey") | |
boolean primaryKey; | |
@XmlValue | |
String data; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment