How can I use jdom to check wether an element is present in a file or not
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开发者_JAVA技巧 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....
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
}
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();
}
List children = root.getChildren("Achild"); int size = children.size();
now check the size wheather it contains any child or not.
精彩评论