【问题标题】:Spring web service returning different results when using JAXB or XML DOM objects使用 JAXB 或 XML DOM 对象时,Spring Web 服务返回不同的结果
【发布时间】:2012-06-15 15:36:53
【问题描述】:

我有一个代表 Web 服务请求的 XML 文档的 JAXB 对象 (ProductRequest)。假设它看起来像这样:

<ProductRequest>
<getProducts/>
</ProductRequests>

对于响应,JAXB 对象 (ProductResponse) 将表示一个 XML 文档,如下所示:

<ProductResponse>
 <productId>1</productId>
 <productName>Oranges</productName>
 <productId>2</productId>
 <productName>Apples</productName>
</ProductResponse>

使用 Spring-WS,我可以使用两种方法向 Web 服务发送请求

使用 JAXB 对象

ProductRequest productRequest = new productRequest();

ProductResponse productResponse = (ProductResponse) webServiceTemplate
                .marshalSendAndReceive(productRequest);

使用纯 XML/DOM

DOMResult domresult = new DOMResult();

webServiceTemplate.sendSourceAndReceiveToResult(source, domresult);  //source represents the XML document as a DOMSource object
Element responseElement = (Element) domresult.getNode().getFirstChild();

当我尝试这两种方法时,结果是不同的。使用 JAXB 对象的第一种方法的结果是

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ProductResponse xmlns="http://mySchema">
 <productId>1</productId>
 <productName>Oranges</productName>
 <productId>2</productId>
 <productName>Apples</productName>
</ProductResponse>

使用 XML Dom 对象的第二种方法的结果是(包括命名空间)

<?xml version="1.0" encoding="UTF-8"?>                 
<ns2:ProductResponse xmlns:ns2="http://mySchema">
 <ns2:productId>1</ns2:productId>
 <ns2:productName>Oranges</ns2:productName>
 <ns2:productId>2</ns2:productId>
 <ns2:productName>Apples</ns2:productName>
</ns2:ProductResponse>

用于 Web 服务响应的模式的标头声明为:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" 
  xmlns:z="http://mySchema" 
  targetNamespace="http://mySchema" 
  elementFormDefault="qualified" 
  attributeFormDefault="unqualified">

    -- Schema elements

</xs:schema>

响应有两个不同

  • JAXB 请求响应的第一行包含条目standalone="yes">
  • JAXB 版本上的元素不以命名空间为前缀
  • 不应该以架构为前缀的元素的响应使用“z”(在架构中定义)而不是 ns2?

我不明白是什么导致了这种差异,因为它们都调用相同的 Web 服务,该服务基于相同的架构生成响应。有任何想法吗?

XML 内容是相同的,但 XML 格式的差异给我带来了问题,因为我无法使用 String.equals() 来比较两者。

【问题讨论】:

    标签: java xml spring xsd jaxb


    【解决方案1】:

    响应相同,只是没有使用命名空间限定。

    附带说明,您的 XML 设计看起来有点不稳定。这样可能会更好;

    <ProductResponse>
      <product>
        <id>1</id>
        <name>Oranges</name>
      </product>
      <product>
        <id>2</id>
        <name>Apples</name>
      </product>
    </ProductResponse>
    

    为什么?因为你不应该依赖元素的顺序。

    【讨论】:

    • 是的,这就是真实文档的格式。以上只是一个例子。
    【解决方案2】:

    结果是一样的。 ns2 只是命名空间的前缀,jaxb 使用默认命名空间,XML Dom 使用前缀 ns2。 xml 文件是等效的,并且它们都对该模式有效。您可以阅读有关 XML 命名空间 here 的更多信息。

    【讨论】:

    • 有什么办法可以让我同时获得命名空间的限定或不限定?
    猜你喜欢
    • 2011-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-21
    • 2011-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多