Pra*_*lar 16 java xpath jaxb unmarshalling
我是JAXB的新手,想知道是否有一种方法可以将XML解组为我的响应对象但使用xpath表达式.问题是我打电话给第三方网络服务,我收到的回复有很多细节.我不希望将XML中的所有细节映射到我的响应对象.我只希望从xml中映射一些细节,使用特定的XPath表达式将其映射到我的响应对象.是否有注释可以帮助我实现这一目标?
例如,考虑以下响应
<root>
<record>
<id>1</id>
<name>Ian</name>
<AddressDetails>
<street> M G Road </street>
</AddressDetails>
</record>
</root>
Run Code Online (Sandbox Code Playgroud)
我只对检索街道名称感兴趣所以我想使用xpath表达式使用'root/record/AddressDetails/street'获取street的值并将其映射到我的响应对象
public class Response{
// How do i map this in jaxb, I do not wish to map record,id or name elements
String street;
//getter and setters
....
}
Run Code Online (Sandbox Code Playgroud)
谢谢
bdo*_*han 20
注意: 我是EclipseLink JAXB(MOXy)的负责人,也是JAXB(JST-222)专家组的成员.
您可以@XmlPath
在此用例中使用MOXy的扩展名.
响应
import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.XmlPath;
@XmlRootElement(name="root")
@XmlAccessorType(XmlAccessType.FIELD)
public class Response{
@XmlPath("record/AddressDetails/street/text()")
String street;
//getter and setters
}
Run Code Online (Sandbox Code Playgroud)
jaxb.properties
要将MOXy用作JAXB提供程序,您需要jaxb.properties
在与域模型相同的程序包中包含一个名为的文件,并带有以下条目(请参阅:http: //blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as -your.html)
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
Run Code Online (Sandbox Code Playgroud)
演示
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Response.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum17141154/input.xml");
Response response = (Response) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(response, System.out);
}
}
Run Code Online (Sandbox Code Playgroud)
产量
<?xml version="1.0" encoding="UTF-8"?>
<root>
<record>
<AddressDetails>
<street> M G Road </street>
</AddressDetails>
</record>
</root>
Run Code Online (Sandbox Code Playgroud)
欲获得更多信息
Mic*_*Kay 10
如果你想要的只是街道名称,只需使用XPath表达式将其作为字符串,并忘记JAXB - 复杂的JAXB机制没有添加任何值.
import javax.xml.xpath.*;
import org.xml.sax.InputSource;
public class XPathDemo {
public static void main(String[] args) throws Exception {
XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();
InputSource xml = new InputSource("src/forum17141154/input.xml");
String result = (String) xpath.evaluate("/root/record/AddressDetails/street", xml, XPathConstants.STRING);
System.out.println(result);
}
}
Run Code Online (Sandbox Code Playgroud)