有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

xml如何在java中使用JAXB创建通用对象

我希望将此xml映射或转换为java对象,并提取xml中的“body”元素,使其成为通用java对象。我不想映射每个字段。我只想要整个请求体和所有元素。我该怎么做

<request>
        <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
            <soap:Header xmlns:dpwsm="http://www.reuqestpower.com/schemas/ryesbs"
                         xmlns:g="http://www.request.com" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
            <k:SoapHeader>
            </k:oapHeader>
        </soap:Header>
        <SOAP-ENV:Body>
            <purchaseOrderRequest xmlns="http://www.somecompany.com/order/PO
        xmlns:addr="http://www.somecomapany.com/order/ADDR>
        <firstname>Fred</firstname>
        <surname>Bloggs</surname>
        <addr:address">
            <addr:addressLine1>2 South Road</addr:address1>
            <addr:addressLine2/>
            <addr:town>Colchester</addr:town>
            <addr:county>Essex</addr:county>
            <addr:postcode>CO8 9SR</addr:postcode>
        </addr:address>
        <telephone>01334 234567</po:telephone>
    </purchaseOrderRequest>
        </SOAP-ENV:Body>
    </SOAP-ENV:Envelope>
</request>

共 (2) 个答案

  1. # 1 楼答案

    可以使用DOM Parser然后检查节点:

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document dom = builder.parse(new InputSource(new StringReader(xml)));
    Node body = dom.getDocumentElement().getElementsByTagName("SOAP-ENV:Body").item(0);
    for(int i=0;i<body.getChildNodes().getLength();i++)
    {
        System.out.println(body.getChildNodes().item(i));
    }
    
    
  2. # 2 楼答案

    如果您可以或想要使用第三方库,可以使用^{}

    org.jsoup.nodes.Document dom = Jsoup.parse(xml, "", Parser.xmlParser());
    Element body = dom.getElementsByTag("SOAP-ENV:Body").get(0);
    for(Element child:body.children())
    {
        System.out.println(child);
    }