我試圖從我的XML數據文件(例如Pantone 100)打印特定節點。我希望它能夠打印出pantone 100的所有屬性,例如所有的顏色和數據,但我不確定如何正確地格式化XPath編譯的方式,以便只取得特定的pantone編號。我是尋找。Java XPath表達式錯誤
編輯:下面輸出的代碼空
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());
}
}
}
輸出 空
這似乎工作,但我得到「空」作爲輸出。不知道什麼是錯的 – ssj3goku878
@ ssj3goku878我已經在Google上搜索了'Node' javadoc,並盡了我最大的努力來更新答案,成爲您正在尋找的東西。嘗試一下並回報。 –