1

I am facing a problem in parsing the following XML:

<key>key 1</key>
<string>string 1</string>
<key>key 2</key>
<string>string 2</string>
<key>key 3</key>
<string>string 3</string>

I have written the following code but I get data only of the first tag in TextView, not the data of tags string2 and string 3. How to parse XML with same name tags?

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final Context mContext = this;
    TextView tv = (TextView) findViewById(R.id.info);

    try {      
         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
         DocumentBuilder db = dbf.newDocumentBuilder();
         AssetManager assetManager = mContext.getAssets();
         InputStream inputStream = assetManager.open("abc.xml");   
         Document doc=db.parse(inputStream);
         doc.getDocumentElement().normalize();
         NodeList nodeList = doc.getElementsByTagName("string"); 


 for (int i = 0; i < nodeList.getLength(); i++) { 
     tv.setText( "\n\n"+ nodeList.item(i).getChildNodes().item(i).getNodeValue()+"\n"); 
     }


        } catch (Exception e) {
          System.out.println("Pasing Excpetion = " + e);
        }


}

1 Answer 1

1

May be your starts from this condition...change your condition from...

for (int i = 0; i < nodeList.getLength(); i++) {

to...

for (int i = 0; i < nodeList.getLength()-1; i++) {

Update:

Change this....

tv.setText( "\n\n"+ nodeList.item(i).getChildNodes().item(i).getNodeValue()+"\n");

to...

tv.setText( "\n\n"+ nodeList.item(i).getChildNodes().item(0).getNodeValue()+"\n");
Sign up to request clarification or add additional context in comments.

2 Comments

Still getting data only in first tag.
How can I avoid some string tags to be included? Like, if I want to include string tags only after tags key 1, key 2 and key 4 and not the string tags after key 3 and key 5. I'll compare the value of key tags to a string, if condition satisfied, append the next node text, otherwise how to ignore the data of next node ? Please help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.