<?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 –
答案 0 :(得分:0)
您可以使用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的一部分。