我正在尝试使用 Java 中的 Xpath 解析 xml 文件。我需要获取属性值为 xml:lang="en" 的文本元素下的所有元素值。
这是我的 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>
Run Code Online (Sandbox Code Playgroud)
这是我的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);
Run Code Online (Sandbox Code Playgroud)
我尝试了一些 Xpath 表达式来获取元素值,例如:
(1) /image/text[@xml:lang='en']/description" 不起作用。
(2) /image/text[@lang='en']/description" 工作正常。
我很想知道第一个 Xpath 表达式有什么问题。
提前致谢。
由于某些(可能是历史的)原因,默认情况下不支持命名DocumentBuilderFactory空间。调用之前必须先调用setNamespaceAware(true)工厂newDocumentBuilder(),因为 XPath 只能在已解析为命名空间感知的 XML 上正常工作。
然后我建议使用该lang函数进行实际测试:
/image/text[lang('en')]/description
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3338 次 |
| 最近记录: |