Я пытаюсь проанализировать XML-файл, используя Xpath в java. Мне нужно получить все значения элементов в текстовом элементе со значением атрибута 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>
Вот моя ява фрагмент кода:
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' ]/описание "отлично работает.
Мне любопытно узнать, в чем проблема с первым выражением 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'? –