繁体   English   中英

JAXB 文件中未编组对象的位置

[英]JAXB location in file for unmarshalled objects

我有一些对象被 JAXB 从 XML 文件中解组。 是否有可能让 JAXB 告诉我或以某种方式找出 XML 文件(行和列)中每个 object 的来源?

此信息在某些时候可用,因为 JAXB 在架构验证错误期间将其提供给我。 但我也想让它可用于经过验证的对象。

您可以通过利用XMLStreamReaderUnmarshaller.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);
        }

    }

}

输入。xml

<?xml version="1.0" encoding="UTF-8"?>
<customer>
    <address/>
</customer>

Output

[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 {

}

了解更多信息

恐怕不是。 JAXB 构建在 XML 解析器之上,这个解析器将建立 XML 文档的逻辑表示,忘记文档的原始字符串表示。

验证步骤在您的字符串仍在读入时完成,因此您的解析器能够给您一条错误消息,告诉您错误的 position。 JAXB 只会绕过该错误消息。 但是一旦 XML 被验证和解析,就只存在逻辑表示。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM