我正在使用w3c dom库来解析XML。这里我需要元素的第三个父元素。例如,在下面的XML中我使用element.getParentNode()
输入XML
<abc cd="1">
<weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0">
<current_conditions>
<condition data="Clear">
<item abc ="1" />
</condition>
<temp_f data="49"/>
<temp_c data="9"/>
</current_conditions>
</weather>
</abc>
我有Element eleItem= /item
并且必须转到父/weather
我这样做:
(Element) eleItem.getParentNode().getParentNode().getParentNode();
是否有其他方法或使用xpath
,因为这似乎不是正确的方法?
像getXPathParent(eleItem, "../../..")
答案 0 :(得分:1)
你快到了。您可以使用以下的XPathFactory
java:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse( new File( "input.xml" ) );
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xpath = xPathFactory.newXPath();
XPathExpression expr = xpath.compile ( "//item/../../..");
Object exprValue = expr.evaluate( doc, XPathConstants.NODE );
if ( exprValue != null && exprValue instanceof Node )
{
Node weatherNode = (Node)exprValue;
System.out.println( weatherNode.getNodeName() );
}
如何运作?
xpath //item/../../..
以递归方式搜索元素item
并获取其第3级父级。
XPathConstants.NODE
中的evaluate
告诉Java XPath引擎将其检索为Node
。
输出将是:
weather
修改强> - 如果您有一个元素作为输入:
以下代码应该为第3个父级提供,其中元素为item
。
public Node getParentNodeUsingXPath( Element element )
{
Node parentNode = null;
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xpath = xPathFactory.newXPath();
String nodeName = element.getNodeName();
String expression = "//" + nodeName + "/../../..";
Object obj = xpath.evaluate(expression, element, XPathConstants.NODE );
if ( obj != null )
{
parentNode = (Node)obj;
}
return parentNode;
}