1

I am using JAXB to save my objects to XML. I have one problem with this though: One of my classes has a String

myclass.getFilePath() // returns an absolute file path

which represents an absolute file path. Before writing this file path to an XML file, I want to relativize it, so I need some kind of preprocessing on my getter. Is that possible using JAXB?

I know I could modify my class and add getRelativePath() and setBasePath() but I would prefer to somehow transform my file path and only do this when exporting to XML.

Update:

@XmlJavaTypeAdapter(MyConverter.class)

should be close to the solution, though I still need a way to pass in an argument (the base path for the relative path) - any hint on this?

Update 2

Probably this does the job: Anyway to pass a constructor parameter to a JAXB Adapter? Will check it now.

4

1 回答 1

0

这似乎与您想要的相似,只是一个想法

class Adapter extends XmlAdapter<String, File> {
    @Override
    public File unmarshal(String v) throws Exception {
        return null;
    }

    @Override
    public String marshal(File v) throws Exception {
        return v.getAbsolutePath();
    }
}

public class Test1 {
    @XmlJavaTypeAdapter(Adapter.class)
    File file = new File("xxx");

    public static void main(String[] args) throws Exception {
        JAXB.marshal(new Test1(), System.out);
    }
}

输出

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<test1>
    <file>D:\workspace1\x\xxx</file>
</test1>
于 2013-04-26T12:18:33.320 回答