如何使用Java

时间:2017-06-07 15:30:00

标签: java xml xpath w3c domparser

我正在使用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, "../../..")

这样的东西

1 个答案:

答案 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;
}