<?xml version='1.0' encoding='UTF-8' standalone='no' ?>
<GTSResponse command="dbget" result="success">
<Record table="Device" partial="true">
<Field name="accountID" primaryKey="true"><![CDATA[UsRentcar]]></Field>
<Field name="deviceID" primaryKey="true"><![CDATA[85412452145214]]></Field>
<Field name="lastOdometerKM">12222.0442925558</Field>
<Field name="description"><![CDATA[Toyota Land Cruser]]></Field>
</Record>
<Record table="Device" partial="true">
<Field name="accountID" primaryKey="true"><![CDATA[UsRentcar]]></Field>
<Field name="deviceID" primaryKey="true"><![CDATA[843254752364]]></Field>
<Field name="lastOdometerKM">4348.48814289997</Field>
<Field name="description"><![CDATA[Chevrolet white]]></Field>
</Record>
我在上面还有另一个带有各种记录的响应节目。如何在每条记录中将两个字段值放在一起。例如:
String [] ListDevice_&_ListDescripcion = { 85412452145214 , Toyota Land Cruser ; 843254752364, Chevrolet white ;....} ;
我该怎么做?这是我的结果.请帮忙!
name="accountID" UsRentcar
name="deviceID" 85412452145214 ; name="lastOdometerKM" 14214.0020055 ; name="description" Toyota Land Cruser ; name="accountID" UsRentcar ; name="deviceID" 843254752364; name="lastOdometerKM" 4348.488142847
name="description" Chevrolet white –
您可以使用 JAXB 来实现此目的:
创建表示 XML 的类:
@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;
}
并像这样使用:
@Test
public void testName() throws Exception {
String f = ...; // path to XML
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()));
}
请注意,您可以使用 JAXB 将 XML 映射到具有 XPATH 的类,注释@XMLPath
,注释是 MOXY 的一部分。