使用此xml示例:
<templateitem itemid="5">
<templateitemdata>%ARN%</templateitemdata>
</templateitem>
<templateitem itemid="6">
<templateitemdata></templateitemdata>
</templateitem>我使用XPath获取和设置节点值。我用来获取节点的代码是:
private static Node ***getNode***(Document doc, String XPathQuery) throws XPathExpressionException
{
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile(XPathQuery);
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
if(nodes != null && nodes.getLength() >0)
return nodes.item(0);
throw new XPathExpressionException("No node list found for " + XPathQuery);
}要获得%ARN%值:"//templateitem@itemid=5/templateitemdata/text()“,并使用getNode方法,我可以获取节点,然后调用getNodeValue()。
除了获得这个值之外,我还想为"templateitem@itemid=6“设置templateitemdata值,因为它是空的。但是我使用的代码不能得到节点,因为它是空的。结果为null。
您知道如何获得节点以便我可以设置值吗?
发布于 2010-04-29 13:41:14
我改变了方法,因为:
public static Node getNode(Document doc, String XPathQuery) throws XPathExpressionException
{
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile(XPathQuery);
Object result = expr.evaluate(doc, XPathConstants.NODE);
Node node = (Node) result;
if(node != null )
return node;
throw new XPathExpressionException("No node list found for " + XPathQuery);
}查询://templateitemdata@itemid=6/templateitemdata
以及setValue方法用于:
public static void setValue(final Document doc, final String XPathQuery, final String value) throws XPathExpressionException
{
Node node = getNode(doc, XPathQuery);
if(node!= null)
node.setTextContent(value);
else
throw new XPathExpressionException("No node found for " + XPathQuery);
}我使用setTextContent()代替setNodeValue()。
https://stackoverflow.com/questions/2736687
复制相似问题