1

我对命名空间有疑问。我需要从公共 api (Prestashop) 中解组。这个 api 有 xml 作为 xlink 类型,如下所示:

<prestashop xmlns:xlink="http://www.w3.org/1999/xlink">
<products>
<product id="1" xlink:href="http://localhost:8080/prestashop/api/products/1"/>
<product id="2" xlink:href="http://localhost:8080/prestashop/api/products/2"/>
</products>
</prestashop>

每个产品的 api 是:

<prestashop xmlns:xlink="http://www.w3.org/1999/xlink">
<product>
<id>
<![CDATA[ 1 ]]>
</id>
<id_manufacturer xlink:href="http://localhost:8080/prestashop/api/manufacturers/1">
<![CDATA[ 1 ]]>
</id_manufacturer>
<id_supplier xlink:href="http://localhost:8080/prestashop/api/suppliers/1">
<![CDATA[ 1 ]]>
</id_supplier>
<id_category_default xlink:href="http://localhost:8080/prestashop/api/categories/3">
<![CDATA[ 3 ]]>
</id_category_default>
</product>
</prestashop>

我生成了两个包,其中包含每个 XML 的 pojo 类。我想从产品列表中获取给定 id 的任何产品的属性。

我在@XMLSchema 中有一个带有命名空间的产品,但是这个命名空间对于一个路径是静态的。我知道那不是这样做的方法。

下面,我的客户类。

public class ClientPrestashop{  

    public static final Logger log = Logger.getLogger(ClientPrestashop.class.getCanonicalName());
    private final String pass = "LA4DKY4AVJUODHCX0H0XH8E7EROV05J6";
    private final String url="http://LA4DKY4AVJUODHCX0H0XH8E7EROV05J6@localhost:8080/prestashop/api/";

    public Object getPrestashopPackageProducts(String path, Class<?> clase) throws JAXBException, Exception{

        ClientConfig config= new DefaultClientConfig();
        Client client = Client.create(config);
        client.addFilter(new HTTPBasicAuthFilter(pass, ""));

        WebResource webresource = client.resource(url + path);
        ClientResponse response = webresource.type(MediaType.APPLICATION_XML).get(ClientResponse.class);

        mostrar(response.getStatus());

        JAXBContext jaxbContext = JAXBContext.newInstance(clase);

        //Crear XMLFilter
        XMLFilter filter = new NamespaceFilter(url+path,true);

        //El XMLReader será encapsulado en nuestro XMLFilter.
        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setNamespaceAware(true);
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        filter.setParent(xr);

        //Modificar UnmarshalerHandler como ContentHandler en XMLFilter 
        Unmarshaller unmarshall = jaxbContext.createUnmarshaller();
        UnmarshallerHandler unmarshallerHandler = unmarshall.getUnmarshallerHandler();
        filter.setContentHandler(unmarshallerHandler);

        //Parse del XML
        InputSource sr = new InputSource(response.getEntityInputStream());
        filter.parse(sr);
        Object presta = unmarshallerHandler.getResult();

        return presta;
    }

这里有代码:https ://github.com/JorgeP86/webservice.git

你能帮我吗?

4

1 回答 1

0

您可以执行以下操作:

@XmlAccessorType(XmlAccessType.FIELD)
public class Product {

    @XmlAttribute
    private int id;

    @XmlAttribute(namespace="http://www.w3.org/1999/xlink")
    private String href;
}

了解更多信息

于 2013-11-27T17:40:00.583 回答