我需要使用Java應用程序中的XPath表達式來查詢XML文檔。我創建了以下類,它接受文件(本地硬盤上XML文檔的位置)和XPath查詢,並返回給定文檔上給定查詢的結果。具有名稱空間的文檔的Java XPath解析器的奇怪行爲
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathException;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
public class XPathResolver
{
public String resolveXPath(File xmlFile, String xpathExpr) throws XPathException, ParserConfigurationException, SAXException, IOException
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(xmlFile);
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile(xpathExpr);
return (String) expr.evaluate(doc, XPathConstants.STRING);
}
}
現在假設我有以下XML文檔。
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Document>
<DocumentFormat>Email</DocumentFormat>
<FileFormat>PDF</FileFormat>
</Document>
評價都/Document/FileFormat
和//FileFormat
回報PDF
(如預期)。
但是,現在假設一個具有名稱空間前綴的文檔,如下所示。
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Document xmlns:file="http://www.example.com/xml/file">
<DocumentFormat>Email</DocumentFormat>
<file:FileFormat>PDF</file:FileFormat>
</Document>
現在/Document/FileFormat
回報PDF
,但//FileFormat
不返回任何東西。
爲什麼我的代碼在命名空間前綴爲空的情況下不能返回預期的輸出,我該如何解決?
您實際上沒有告訴我們您正在使用哪種XPath處理器。如果切換到另一個,請檢查您是否得到不同的答案。 –