0

我有一个这样的 XML 文件:

<?xml version="1.0"?>
<settings>
  <mail id="sender">
       <host>content here</host>
       <port>25</port>
       <account>tmt@example.com</account>
       <password>password</password>
  </mail>

  <mail id="receiver">
    <account>tmt@example.com</account>
  </mail>

  <mail id="support">
    <account>tmt@example.com</account>
  </mail>
</settings>

我怎样才能得到attribute每个element,解析每个的内容element并将内容保存在SharedPreference

这是我到目前为止所做的:

承包商:

    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(); 

}

还有我的doInBackground方法

@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);
    }
}

LogCat我知道有三个elements,这是正确的。

4

1 回答 1

1
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 "";
        }

    }
于 2012-08-24T12:22:07.553 回答