Retrieving specific elements from XML string using java

Below is my code. I am able to parse xml, I am getting all the values if it in xml - For eg:- Part No i am getting all the values since it is in xml. While i am accessing MODEL, application terminates. How to check whether model tag is there or not and i want to check whether if tag is there value is empty or not.

PartNo[i].setText(el.getElementsByTagName("PART_NO").item(0).getTextContent());

if(el.getNodeName().contains("MODEL"))
{
    Model[i].setText(el.getElementsByTagName("MODEL").item(0).getTextContent());
} 

The XML document looks like this:

<root>
  <DataSet>
    <PartNo>aaa</PartNo>
    <Model>bbbb</Model>
  </DataSet>
  <DataSet>
    <PartNo>aaa</PartNo>
  </DataSet>
</root>

Answers


Your call el.getNodeName().contains("MODEL")) is checking whether the String node name of el contains "MODEL", which is obviously wrong.

Reading between the lines, I think you want to check is there is a corresponding Model element for each PartNo element, which can be done like this with a DOM parser:

NodeList partNoElements = document.getElementsByTagName("PartNo");
for (int i = 0; i < partNoElements.getLength(); i++)
{
  Element partNoElement = partNoElements.item(i);

  PartNo[i].setText(partNoElement.getTextContent());

  Element modelElement = (Element)partNoElement.getNextSibling();
  if (modelElement != null && modelElement.getNodeName().equals("Model"))
  {
    Model[i].setText(modelElement.getTextContent());
  }
}

NOTE: this relies on the order of the elements always being as you've listed, which should be enforced by a schema if you're going to use this code.


Need Your Help

MainActivity.java all grayed out

java android

I added splash.xml and did project - clean which led to losing R.java. The cause was I have an mp3 file in raw folder which was giving error. I deleted that mp3 file and got back the R.java. Now my

When trying to Install application remotely into an iPhone through mdm .mobileconfig file, returns "invalid profile" error

ios plist mdm

When i tried to install application remotely into an iPhone using the .mobileconfig file as mentioned in the question