Search code examples
javaxmljdomjdom-2

getting content between two tags XML using jdom


i'm trying to get content between tag <catalog> </catalog> as this is xml file :

<test1>
</test1>
<catalog>
  <book id="bk101">
  <author>Gambardella, Matthew</author> 
  <title>XML Developer's Guide</title> 
  <genre>Computer</genre> 
  <price>44.95</price> 
  </book>
  <book id="bk102">
  <author>Ralls, Kim</author> 
  <title>Midnight Rain</title> 
  <genre>Fantasy</genre> 
  <price>5.95</price> 
  </book>
</catalog>

and getting as result only this :

<book id="bk101">
      <author>Gambardella, Matthew</author> 
      <title>XML Developer's Guide</title> 
      <genre>Computer</genre> 
      <price>44.95</price> 
      </book>
      <book id="bk102">
      <author>Ralls, Kim</author> 
      <title>Midnight Rain</title> 
      <genre>Fantasy</genre> 
      <price>5.95</price> 
      </book>

i begin to learn about jdom ,but i can reach this result i only know basics operations , could any one have an idea about how to do it , and thanks in advance. i try this :

public static void read() throws JDOMException, IOException{
        SAXBuilder reader = new SAXBuilder();
        Document doc = reader.build(new File("C:\\Users\\HC\\Desktop\\dataset\\book.xml"));
        racine = doc.getRootElement();

        String root = racine.getName();
        Element catalog = racine.getChild("catalog");
        List nodes = catalog.getChildren();
        Iterator i = nodes.iterator();
        while(i.hasNext()){
            Element courant = (Element) i.next();
         // i want here keeping all tags inside the tag catalog
         System.out.print(courant.getContent());

        }

    }

i got only result like this :

[[Text: 
      ], [Element: <author/>], [Text: 
      ], [Element: <title/>], [Text: 
      ], [Element: <genre/>], [Text: 
      ], [Element: <price/>], [Text: 

   ]][[Text: 
      ], [Element: <author/>], [Text: 
      ], [Element: <title/>], [Text: 
      ], [Element: <genre/>], [Text: 
      ], [Element: <price/>], [Text: 

Solution

  • Below is the code of how to do it with vtd-xml

      import com.ximpleware.*;
        public class getContent {
            public static void main(String s[]) throws VTDException{
                VTDGen vg = new VTDGen();
                if (!vg.parseFile("C:\\Users\\HC\\Desktop\\dataset\\book.xml", false))
                    return;
                VTDNav vn = vg.getNav();
                if (vn.toElement(VTDNav.FIRST_CHILD, "book")){
                    long l = vn.getContentFragment();
                    System.out.println( "book content ==> ");
                    System.out.println(vn.toString((int)l, (int)(l<<32)));
                }
            }
        }