【发布时间】:2014-02-19 09:37:09
【问题描述】:
我正在尝试在 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>
这是我的java代码sn-p:
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) /image/text[@xml:lang='en']/description" 这不起作用。
(2) /image/text[@lang='en']/description" 工作正常。
我很想知道第一个 Xpath 表达式有什么问题。
提前致谢。
【问题讨论】:
-
参考stackoverflow.com/questions/5518096/…,您的命名空间是否正确注册?
-
命名空间确实是问题所在。你能展示一些java代码吗?
-
您是否考虑过使用专门为
xml:lang设计的langfunction? -
@Smutje :感谢您指出命名空间注册。