簡體   English   中英

如何使用Java獲取xml中元素的第N個父元素

[英]How to get Nth parent for an element in xml using Java

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

你快到了 您可以使用Java的XPathFactory ,如下所示:

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並獲取其第三級父級。

evaluateXPathConstants.NODE告訴Java XPath引擎將其檢索為Node

輸出將是:

weather

編輯: -如果您有一個元素作為輸入:

以下代碼應為第3個父級,其中element是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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM