简体   繁体   English

使用JDOM获取xml文件中元素的值

[英]get value of element in xml-file using JDOM

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 但是我得到空值

You must have 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());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM