2

I have xml-file

<?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

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

Ray
  • 1,788
  • 7
  • 55
  • 92
  • 2
    Hi Ray, one issue that's probably confusing you is the Namespace on the element. You will need to supply a Namespace instance to all your JDOM methods if you want to be able to select the Elements. For example, rootNode.getChild("category") will return nothing, but rootNode.getChild("category", Namespace.getNamespace("http://www.myapp.com/shop")) will return the category Element – rolfl Aug 30 '12 at 15:00

1 Answers1

9

You must have to use getDescendants(Filter<F>) method to select a specific Element

Element root = document.getRootElement();
ElementFilter filter = new org.jdom2.filter.ElementFilter("model");
for(Element c : root.getDescendants(filter)) {
    System.out.println(c.getTextNormalize());
}
Jérèm Le Blond
  • 645
  • 5
  • 23
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186