find whether an element exists by a particular tag name in XML
Asked Answered
H

5

8

I have an XML file where some sub tags (child node elements) are optional. e.g.

<part>
   <note>
       </rest>
   </note>

   <note>
       <pitch></pitch>
   </note>

   <note>
       <pitch></pitch>
   </note>
</part>

But when I read the XML files by tags, it throws a NullPointerException - since some sub-tags are optional (e.g. rest and pitch in above example). How can I filter this out? I couldn't come across any methods to find whether an element exists by a particular tag name. Even if I have a condition to check whether getElementsByTagName("tag-name") method not returns NULL - still it goes in the condition body and obviously throw the exception. How may I resolve this?

The java code is:

if(fstelm_Note.getElementsByTagName("rest")!=null){
    if(fstelm_Note.getElementsByTagName("rest")==null){
        break;
    }
    NodeList restElmLst = fstelm_Note.getElementsByTagName("rest");
    Element restElm = (Element)restElmLst.item(0);
    NodeList rest = restElm.getChildNodes();

    String restVal = ((Node)rest.item(0)).getNodeValue().toString();

}else if(fstelm_Note.getElementsByTagName("note")!=null){
    if(fstelm_Note.getElementsByTagName("note")==null){
        break;
    }

    NodeList noteElmLst = fstelm_Note.getElementsByTagName("note");
    Element noteElm = (Element)noteElmLst.item(0);

    NodeList note = noteElm.getChildNodes();
    String noteVal = ((Node)note.item(0)).getNodeValue().toString();
}

Any insight or suggestions are appreciated. Thanks in advance.

Hardin answered 8/7, 2010 at 9:7 Comment(1)
Not enough information. Post the code that's having the problem, and indicate where the NPE is thrown.Rachellrachelle
E
14

I had this very same problem (using getElementsByTagName() to get "optional" nodes in an XML file), so I can tell by experience how to solve it. It turns out that getElementsByTagName does not return null when no matching nodes are found; instead, it returns a NodeList object of zero length.

As you may guess, the right way to check if a node exists in an XML file before trying to fetch its contents would be something similar to:

NodeList nl = element.getElementsByTagName("myTag");
if (nl.getLength() > 0) {
    value = nl.item(0).getTextContent();
}

Make sure to specify a "default" value in case the tag is never found.

Empirin answered 4/11, 2013 at 16:18 Comment(0)
A
1

It may be that your NodeLists are not null, but are empty. Can you try changing your code like this and see what happens?

NodeList restElmLst = fstelm_Note.getElementsByTagName("rest");
if (restElmLst != null && !restElmLst.isEmpty())
{
    Element restElm = (Element)rests.item(0);
...

etc. (Doublecheck syntax etc., since I'm not in front of a compiler.)

Agora answered 10/7, 2010 at 2:21 Comment(0)
D
1

Your requirements are extremely unclear but I would very likely use the javax.xml.xpath package to parse your XML document with the XML Path Language (XPath).

Have a look at:

But you should try to explain the general problem you are trying to solve rather than the specific problem you're facing. But doing so, 1. you will probably get better answers and 2. the current chosen path might not be the best one.

Destitution answered 10/7, 2010 at 3:3 Comment(1)
Hi Pasacal, thanks for your suggestions. Is XPath a web service (which requires internet for the code to run)? Can I query the XML document using XPath? Is it similar to XQuery? I had some issues with configuring XQuery - so couldn't work it out. Can you pls suggest some tutorials where I can make use for XPath or XQuery? Thanks for your time.Hardin
M
0

Try something like below

bool hasCity = OrderXml.Elements("City").Any();

where OrderXml is parent element.

Meteoritics answered 11/6, 2015 at 6:8 Comment(0)
D
0

First you need to create the nodelist and then check the length of nodelist to check whether the current element exists or not in the xml string.

NodeList restElmLst = fstelm_Note.getElementsByTagName("rest");

if (restElmLst.getLength() > 0) {
    String restVal = restElm.getElementsByTagName("rest").item(0).getTextContent(); 
}                               
Disrespectful answered 3/8, 2017 at 4:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.