我在命名空间方面遇到问题。 我需要从公共(public) api (Prestashop) 中解码。 该 api 具有 xlink 类型的 xml,如下所示:
<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 的任何产品的属性。
我有一个产品,其 namespace 位于 @XMLSchema 中,但该 namespace 仅针对一个路径是静态的。我知道这不是办法。
下面是我的客户类。
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
你能帮我一下吗?
最佳答案
您可以执行以下操作:
@XmlAccessorType(XmlAccessType.FIELD)
public class Product {
@XmlAttribute
private int id;
@XmlAttribute(namespace="http://www.w3.org/1999/xlink")
private String href;
}
了解更多信息
关于java - 贾克斯布 + Jersey 。如何解码多个命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20248920/