我正在检查一个带有 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] [对象] 不是线程安全的,也不是可重入的。
有任何想法吗?