2

I have an XML file like this:

<?xml version="1.0" encoding="utf-8"?>
<RootElement>
 <Achild>
  .....
 </Achild>
 </RootElement>

How can I check if the File contains Achild element or not..?

            final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    // Use the factory to create a builder
    try {
        final DocumentBuilder builder = factory.newDocumentBuilder();
        final Document doc = builder.parse(configFile);
        final Node parentNode = doc.getDocumentElement();
        final Element childElement = (Element) parentNode.getFirstChild();
                    if(childElement.getNodeName().equalsIgnoreCase(....

buts its giving me error on childElement is null....

Saurabh Kumar
  • 16,353
  • 49
  • 133
  • 212

3 Answers3

1
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(new File("foo.xml"));

XPath xPath = XPath.newInstance("/RootElement/Achild");

/*If you want to find all the "Achild" elements 
and do not know what the document structure is, 
use the following XPath instead(less efficient):
XPath xPath = XPath.newInstance("//Achild");
*/

Element aChild = (Element) xPath.selectSingleNode(document);

if(aChild == null){
  //There is at least one "Achild" element in the document
} else{
  //No "Achild" elements found
}
Mads Hansen
  • 63,927
  • 12
  • 112
  • 147
0
List children = root.getChildren("Achild");
int size = children.size();

now check the size wheather it contains any child or not.

Rupok
  • 2,062
  • 16
  • 16
  • So far we've got "wether" and "weather"...anyone want to throw a "whether" into the mix? – Paul Jul 11 '11 at 12:19
0

In your code u are just creating a builder, but what does it build ?? u dont' specifiy the file used to uold the DOM Tree... Below a small example using JDom.. But to make searches and much more XPATH and XQuery are pretty amazing ..

    try {
        SAXBuilder builder = new SAXBuilder();
        File XmlFile = new File("Xml_File_Path");
        docXml = builder.build(XmlFile.getPath());
        Element root = docXml.getRootElement();
        if (root.getChildren("aChild") == Null)
            do_whateva_you_want
        else
            great_i_can_keep_up

    } catch (JDOMException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
Nedved
  • 35
  • 6