MOXy 目前不支持通配符,@XmlPath但下面是一种您可以使用StreamReaderDelegate.
领域模型
根
package forum17527941;
import java.util.Date;
import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.*;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {
@XmlPath("s:stackoverflow/s:information/s:date/text()")
@XmlSchemaType(name="date")
private Date date = new Date();
@XmlPath("s:stackoverflow/s:information/s:name/text()")
private String name;
}
包信息
@XmlSchema(
namespace="http://www.example.eu/test",
xmlns={
@XmlNs(prefix="s", namespaceURI="http://www.example.eu/test")
},
elementFormDefault=XmlNsForm.QUALIFIED)
package forum17527941;
import javax.xml.bind.annotation.*;
演示代码
演示
package forum17527941;
import javax.xml.bind.*;
import javax.xml.stream.*;
import javax.xml.stream.util.StreamReaderDelegate;
import javax.xml.transform.stream.StreamSource;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Root.class);
XMLInputFactory xif = XMLInputFactory.newFactory();
StreamSource xml = new StreamSource("src/forum17527941/input.xml");
XMLStreamReader xsr = xif.createXMLStreamReader(xml);
xsr = new StreamReaderDelegate(xsr) {
@Override
public String getLocalName() {
String localName = super.getLocalName();
if("resource".equals(localName) || "data".equals(localName) || "container".equals(localName)) {
return "stackoverflow";
}
return localName;
}
};
Unmarshaller unmarshaller = jc.createUnmarshaller();
Root root = (Root) unmarshaller.unmarshal(xsr);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "http://www.example.eu/test ResourceSchema.xsd");
marshaller.marshal(root, System.out);
}
}
输入.xml
使用以下输入,StreamReaderDelegate将导致resource元素被报告为stackoverflow映射的匹配项。
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<s:root xsi:schemaLocation="http://www.example.eu/test ResourceSchema.xsd" xmlns:s="http://www.example.eu/test" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<s:resource>
<s:information>
<s:date>2013-07-04</s:date>
<s:name>This example does not work</s:name>
</s:information>
</s:resource>
</s:root>
输出
输出将匹配域模型中的映射。
<?xml version="1.0" encoding="UTF-8"?>
<s:root xsi:schemaLocation="http://www.example.eu/test ResourceSchema.xsd" xmlns:s="http://www.example.eu/test" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<s:stackoverflow>
<s:information>
<s:date>2013-07-04</s:date>
<s:name>This example does not work</s:name>
</s:information>
</s:stackoverflow>
</s:root>
了解更多信息