簡體   English   中英

Java XPath表達式錯誤

[英]Java XPath Expression error

我試圖從我的XML數據文件(例如Pantone 100)中打印特定的節點。 我希望它打印出Pantone 100中的所有屬性,例如所有顏色和它們擁有的數據,但是我不確定如何正確格式化XPath編譯方式,從而只提取特定的Pantone編號。尋找。

編輯:下面的代碼輸出為空

XML數據

<inventory>
    <Product pantone="100" blue="7.4" red="35" green="24"> </Product>
    <Product pantone="101" blue="5.4" red="3" rubine="35" purple="24"> </Product>
    <Product pantone="102" orange="5.4" purple="35" white="24"> </Product>
    <Product pantone="103" orange="5.4" purple="35" white="24"> </Product>
    <Product pantone="104" orange="5.4" purple="35" white="24"> </Product>
    <Product pantone="105" orange="5.4" purple="35" white="24"> </Product>
    <Product pantone="106" black="5.4" rubine="35" white="24" purple="35" orange="5.4"> </Product>
</inventory>

import org.w3c.dom.*;
import javax.xml.xpath.*;
import javax.xml.parsers.*;
import java.io.IOException;
import org.xml.sax.SAXException;

public class XPathDemo {

    public static void main(String[] args)
            throws ParserConfigurationException, SAXException,
            IOException, XPathExpressionException {

        DocumentBuilderFactory domFactory
                = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true);
        DocumentBuilder builder = domFactory.newDocumentBuilder();
        Document doc = builder.parse("data.xml");
        XPath xpath = XPathFactory.newInstance().newXPath();
        // XPath Query for showing all nodes value
        XPathExpression expr = xpath.compile("/inventory/Product[@pantone='100']");

        Object result = expr.evaluate(doc, XPathConstants.NODESET);
        NodeList nodes = (NodeList) result;
        for (int i = 0; i < nodes.getLength(); i++) {
            System.out.println(nodes.item(i).getNodeValue());
        }
    }
}

輸出空

我不是xpath的專家(今天從字面上學到了它),所以我對此不是100%肯定,但是您有/inventory/product/pantone/text(@=100) ,請嘗試以下操作:

/inventory/Product[@pantone='100']

據我了解,這將使Product與屬性pantone等於"100"匹配。

至於打印數據,我不確定,但是希望這能使您走上正確的道路。

編輯:簽出此頁面: Node 它是Node類型的javadoc。 正如geert3在他/她的回答中所說, getNodeValue()返回節點的值,在這種情況下,它是元素的值,而不是屬性(例如:在<element>value</element>中,元素的值element是值),在您的情況下為null因為它為空(如果認為類型為String,則可能是""而不是null ?)。

嘗試調用Node#getAttributes() ,然后使用NamedNodeMap#item(int)遍歷NamedNodeMap以獲得Node 這些應該是屬性(我想,如果我正確理解API的話)。 getNodeName()應該是屬性的名稱(例如pantone ),而getNodeValue()應該是屬性的值(例如100 )。

輸出為null,因為getNodeValue在此處不適用。 getTextContent將為您提供開始標記和結束標記之間的文本,例如,在此示例中為FOOBAR:

<Product pantone="100" blue="7.4" red="35" green="24">FOOBAR</Product>`.

但是,如果要打印結果集的所有屬性值:

    NodeList nodes = (NodeList)result;
    for (int i = 0; i < nodes.getLength(); i++)
    {
        NamedNodeMap a = nodes.item(i).getAttributes();
        for (int j=0; j<a.getLength(); j++)
            System.out.println(a.item(j));
    }

或使用a.item(j).getNodeName()a.item(j).getNodeValue()分別檢索屬性名稱或值。

暫無
暫無

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

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