Reputation: 1199
I am having a XML file like
<parent>
<child1>
<child2>
<name>name</name>
<value>
<item>value></item>
</value>
</child2>
</child1>
<child1>
<value>
<item>value></item>
</value>
</child1>
</parent>
Here i need to check, whether child2 node is missing or not.
My java code is like
File xmlfile = new File ("sample.xml");
DocumentBuilderFactory dbfaFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = dbfaFactory.newDocumentBuilder();
Document doc = documentBuilder.parse(xmlfile);
NodeList child1= doc.getElementsByTagName("child1");
for( int i=0; i<child1.getLength(); i++)
{
NodeList child1= doc.getElementsByTagName("child1");
if(!doc.getElementsByTagName("child2").equals(null))
{
System.out.println("Not Equal to null");
else
{
System.out.println("Equal to null");
}
}
But every time i am getting Not Equal to null, even though child2 node is missing in the XML.
Here child2 is missing
<child1>
<value>
<item>value></item>
</value>
</child1>
Thanks.
Upvotes: 0
Views: 1483
Reputation: 3567
You might find XPath is well-suited for this task:
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(new File("sample.xml"));
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xPath = xPathFactory.newXPath();
XPathExpression xPathExpression = xPath.compile("/parent/child1/child2");
NodeList nodeList = (NodeList) xPathExpression.evaluate(document, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
System.out.println(node.getNodeName());
}
If child2
is there, then nodeList.getLength()
will equal one (or the number of child2
elements there are under child1
), otherwise it will be zero.
If you want all the instances where child1
has a child that is not child2
you can use:
/parent/child1/*[not(self::child2)]
as your XPath expression. If you only want to count the number of times that child1
has any children that are not child2
then you can use:
/parent/child1/*[not(self::child2)][1]
Upvotes: 0
Reputation: 3390
This code cannot work: doc.getElementsByTagName("child2")
traverses the whole XML, i.e. it returns ANY child2 it can find.
Either try using child1.getElementsByTagName("child2")
, or consider using a "sane" XML library. XOM for example has a function getChildElements(String name)
which works in the way you would expect.
EDIT: As Jenson noted, you might run into NullPointerException
s with that null check clause, use child1.getElementsByTagName("child2") != null
instead.
Upvotes: 1