Tobias Moe Thorstensen
Tobias Moe Thorstensen

Reputation: 8981

Getting content of a XML node by the attribute

I have a XML file like this:

<?xml version="1.0"?>
<settings>
  <mail id="sender">
       <host>content here</host>
       <port>25</port>
       <account>[email protected]</account>
       <password>password</password>
  </mail>

  <mail id="receiver">
    <account>[email protected]</account>
  </mail>

  <mail id="support">
    <account>[email protected]</account>
  </mail>
</settings>

How can I get the attribute of each element, parse the content of each element and save the content in SharedPreference

This is what I've done so far:

The Contructor:

    public ReadConfig(Context context, ProgressBar progressBar) throws ParserConfigurationException, SAXException, IOException   {

    this.context = context; 
    this.progressBar = progressBar;


    folders = new CreateApplicationFolder();
    dbf = DocumentBuilderFactory.newInstance();
    db = dbf.newDocumentBuilder();
    doc = db.parse(new File(folders.getPathToNode() + "/settings_config.xml")); 
    doc.getDocumentElement().normalize(); 

}

And my doInBackground method

@Override
protected String doInBackground(String... params)  {

        Log.i("ROOT NODE: ", doc.getDocumentElement().getNodeName()); 

    NodeList listOfMail = doc.getElementsByTagName("mail"); 
    int totalMail = listOfMail.getLength(); 
    Log.i("LENGTH: ", Integer.toString(totalMail)); 


    for(int i = 0; i < totalMail; i++) {

        Node firstMailSetting = listOfMail.item(i);
    }
}

From the LogCat I know that there are three elements, which is correct.

Upvotes: 0

Views: 117

Answers (1)

MAC
MAC

Reputation: 15847

import org.w3c.dom.Element;

for(int i = 0; i < totalMail; i++) {
        Node firstMailSetting = listOfMail.item(i);
        Element e = (Element) firstMailSetting ;
        String acc = getTagValue("account", e); <-----
    }


private String getTagValue(String sTag, Element eElement) {
    try {
         NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
         Node nValue = (Node) nlList.item(0);
         return nValue.getNodeValue();
        } 
    catch (Exception e) {
            return "";
        }

    }

Upvotes: 1

Related Questions