我想解析一個xml文件,在java中使用Xpath。我需要獲取屬性值爲xml:lang =「en」的文本元素下的所有元素值。如何獲取包含冒號的xml屬性值?
這裏是我的xml文件:
<?xml version="1.0" encoding="UTF-8" ?>
<image id="10001" file="images/2/10001.png">
<name>Lake two mountains.png</name>
<text xml:lang="en">
<description />
<comment />
<caption article="text/en/4/335157">Location map of Lake of Two Mountains. </caption>
</text>
<text xml:lang="de">
<description/>
<comment />
<caption article="text/de/5/441485">Lage des Lac des Deux Montagnes (ganz rechts liegt Montréal)</caption>
</text>
<text xml:lang="fr">
<description />
<comment />
<caption />
</text>
<comment>({{Information |Description= Location map of Lake of Two Mountains in Quebec, Canada. |Source= based on Image:Oka map with roads.png. |Date= |Author= P199 |Permission= |other_versions= }})</comment>
<license>GFDL</license>
</image>
這裏是我的Java代碼片斷:
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
Document xmlDocument = null;
try {
builder = builderFactory.newDocumentBuilder();
}
catch (ParserConfigurationException e) {
e.printStackTrace();
}
try {
xmlDocument = builder.parse(new FileInputStream(fileEntry.getAbsolutePath()));
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
XPath xPath = XPathFactory.newInstance().newXPath();
//prepare node expressions
String nameExpr = "/image/name";
String descriptionExpr = "/image/text[@lang='en']/description";
String captionExpr = "/image/text[@lang='en']/caption";
String commentExpr = "/image/text[@lang='en']/comment";
//read a string value
String name = xPath.compile(nameExpr).evaluate(xmlDocument);
String description = xPath.compile(descriptionExpr).evaluate(xmlDocument);
String caption = xPath.compile(captionExpr).evaluate(xmlDocument);
String comment = xPath.compile(commentExpr).evaluate(xmlDocument);
我嘗試了一些XPath表達式得到的元素值,例如:
(1)/圖片/文字[@xml:lang ='en']/description「
(2)/ image/text [@ lang ='en' ]/description「工作正常。
我很想知道第一個Xpath表達式有什麼問題。
在此先感謝。
指的http://stackoverflow.com/questions/5518096/xpath-to-select-value-of-sibling-attribute -with-namespace,是否正確註冊了你的命名空間? – Smutje
命名空間確實是問題。你能展示一些java代碼嗎? – Robin
您是否考慮過使用['lang'函數](http://www.w3.org/TR/xpath/#function-lang),因爲它是專門爲'xml:lang'設計的? –