如何使用JAXB从XML获取所需的标记

时间:2017-07-28 05:20:20

标签: java xml jaxb

如果我有一个带有巨大标题标签的XML,但我只需要获取对象列表dppc和子对象ppc。请告知如何仅从节点dppc获取值。

<SOAPENV:Envelope xmlns:SOAPENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<SOAPENV:Body>
    <rpc:distributeObject xmlns:SOAPENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:rpc="http://company.xxx.com/Distributed/Object">
        <standardHeader xmlns="http://wsi.nat.bat.com/2005/06/StandardHeader/">
            <dppc>
                <ppc>
                    <productName>Export1</productName>
                </ppc>
                <ppc>
                    <productName>Export2</productName>
                </ppc>
            </dppc>
        </standardHeader>
    </rpc:distributeObject>
</SOAPENV:Body>

请找到以下代码来解组​​它

String example =

                      "<SOAPENV:Envelope xmlns:SOAPENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><SOAPENV:Body><rpc:distributeObject xmlns:SOAPENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:rpc=\"http://company.xxx.com/Distributed/Object\"><standardHeader xmlns=\"http://wsi.nat.bat.com/2005/06/StandardHeader/\"><dppc><ppc><productName>Export1</productName></ppc><ppc><productName>Export2</productName></ppc></dppc></standardHeader></rpc:distributeObject></SOAPENV:Body>";


message = MessageFactory.newInstance().createMessage(null,
                    new ByteArrayInputStream(example.getBytes()));
Unmarshaller unmarshaller = JAXBContext.newInstance(Dppc.class).createUnmarshaller();
Dppc dppc = (Dppc)unmarshaller.unmarshal(message.getSOAPBody().extractContentAsDocument());
dppc.getPPC();

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
class Dppc{
@XmlPath("rpc:distributeObject/standardHeader/dppc")
private List<PPC> ppC;


    public List<PPC> getPPC() {
        return ppC;
    }


    public void setPPC(List<PPC> ppC) {
        this.ppC= ppC;
    }
}
class PPC {
       String productName;
        //getter & setters;
}

我也创建了一个package-info文件,但它无法正常工作。

1 个答案:

答案 0 :(得分:0)

使用纯JAXB实现这是不可能的,因为默认情况下JAXB不支持XPath。

一种可能的解决方案是使用支持@XmlPath注释的EclipseLink(MOXy)

使用该注释,可以在XML中定义元素的路径。为了让您的XML只读取dppc元素和子元素,您的类看起来像这样(未经测试):

import javax.xml.bind.annotation.*;
import org.eclipse.persistence.oxm.annotations.XmlPath;

@XmlRootElement(name="SOAPENV:Body")
public class MainElement{
    @XmlPath("rpc:distributeObject/standardHeader/dppc")
    DPPC dppc; 

    //getter and setters
}

dppcppc类相同。

MOXy链接为您提供了一些很好的例子。

相关问题