0

我正在检查一个带有 xml 元素的元素,如果不存在,将默认一个值。

这是来自 Websphere 7 上的 JAXWS 的 Web 服务调用,作为 org.apache.xerces.dom.ElementNSImpl。

// instantiate xpath
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xPath = xPathFactory.newXPath();
xPath.setNamespaceContext(new NamespaceContext() {
    public String getNamespaceURI(String prefix) {
    if ("ns".equals(prefix))
        return PROVIDER_NAMESPACE;
    else
        return XMLConstants.NULL_NS_URI;
    }
    public String getPrefix(String uri) {
        return null; // n/a
    }
    public Iterator<?> getPrefixes(String uri) {
        return null; // n/a
    }
});

// Check if date is populated
XPathExpression declarationDateXpath = xPath.compile("//ns:Provider/ns:DeclarationDate");
Node dateNode = (Node) providerDateXpath.evaluate(node, XPathConstants.NODE);
if (dateNode == null) {
    // if not there, add the node
    Document doc = node.getOwnerDocument();
    dateNode = doc.createElementNS(PROVIDER_NAMESPACE, "DeclarationDate");

    XPathExpression providerXPath = xPath.compile("//ns:Provider");    
    Node providerNode = (Node) providerXPath.evaluate(node, XPathConstants.NODE);
    providerNode.appendChild(dateNode);
}

// Check value & set default if necessary
if (dateNode.getTextContent() == null || "".equals(dateNode.getTextContent())) {
    // date not set, defaulting to today
    dateNode.setTextContent(today);
} 

如您所见,我在每次调用时都尽可能多地实例化所有内容。

第一个 Web 服务调用,它返回节点。第二个 Web 服务调用,它为两个 xpath 都返回 null。

根据javadoc “XPath [和 XPathExpression] [对象] 不是线程安全的,也不是可重入的。

有任何想法吗?

4

1 回答 1

0

好吧。我已经想通了,我已经成功了。

这是xpath。好吧,准确地说,这是第二轮的 xpath 。

我将 xpath 从"//ns:Provider/ns:DeclarationDate"ns:Provider根在哪里)缩短到"//ns:DeclarationDate".

在 JAXP 的 WebSphere 7 实现中的某个地方会存在导致此问题的缺陷,但不可能/不值得进​​一步调查。

我希望这对将来的某人有所帮助...

于 2011-08-31T23:29:31.057 回答