我有一些对象通过JAXB从XML文件中取消编组。在XML文件中(行和列),每个对象可能来自哪里,JAXB是否可以告诉我或以某种方式找出?
这些信息在某个时候是可用的,因为在模式验证错误期间,JAXB会将其提供给我。但我也希望对已验证的对象进行验证。
您可以通过利用XMLStreamReader
和Unmarshaller.Listener
在JAXB中完成此操作:
演示
package forum383861;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.Unmarshaller.Listener;
import javax.xml.stream.Location;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Customer.class);
XMLInputFactory xif = XMLInputFactory.newFactory();
FileInputStream xml = new FileInputStream("src/forum383861/input.xml");
XMLStreamReader xsr = xif.createXMLStreamReader(xml);
Unmarshaller unmarshaller = jc.createUnmarshaller();
LocationListener ll = new LocationListener(xsr);
unmarshaller.setListener(ll);
Customer customer = (Customer) unmarshaller.unmarshal(xsr);
System.out.println(ll.getLocation(customer));
System.out.println(ll.getLocation(customer.getAddress()));
}
private static class LocationListener extends Listener {
private XMLStreamReader xsr;
private Map<Object, Location> locations;
public LocationListener(XMLStreamReader xsr) {
this.xsr = xsr;
this.locations = new HashMap<Object, Location>();
}
@Override
public void beforeUnmarshal(Object target, Object parent) {
locations.put(target, xsr.getLocation());
}
public Location getLocation(Object o) {
return locations.get(o);
}
}
}
input.xml
->input.xml
<?xml version="1.0" encoding="UTF-8"?>
<customer>
<address/>
</customer>
输出
[row,col {unknown-source}]: [2,1]
[row,col {unknown-source}]: [3,5]
客户
package forum383861;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Customer {
private Address address;
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
地址
package forum383861;
public class Address {
}
更多信息
XMLStreamReader
和 Unmarshaller.Listener
来获得这种类型的支持:https://dev59.com/ZFrUa4cB1Zd3GeqPilFj#7081390 - bdoughan