java 使用 JDOM 获取 xml 文件中元素的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12199231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 08:00:57 来源:igfitidea点击:
get value of element in xml-file using JDOM
提问by Ray
I have xml-file
我有 xml 文件
<?xml version="1.0" encoding="UTF-8"?>
<products xmlns="http://www.myapp.com/shop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.myapp.com/shop shop.xsd">
<category name="yyy">
<subcategory name="yyy1">
<goods name="yyy11">
<model>ferrari</model>
</goods>
</subcategory>
</category>
</products>
i try to get value of element <model>
as
我尝试将元素的值<model>
作为
SAXBuilder builder = new SAXBuilder();
File xmlProductFile = new File("shop.xml");
Document document = builder.build(xmlProductFile);
Element rootNode = document.getRootElement();
String category = rootNode.getChild("model").getText();
But I get empty value
但我得到空值
回答by adatapost
You musthave to use getDescendants(Filter<F>)
method to select a specific Element
您必须使用getDescendants(Filter<F>)
方法来选择特定的Element
Element root = document.getRootElement();
ElementFilter filter = new org.jdom2.filter.ElementFilter("model");
for(Element c : root.getDescendants(filter)) {
System.out.println(c.getTextNormalize());
}