通过属性获取XML节点的内容

时间:2012-08-24 12:18:02

标签: android xml

我有一个像这样的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的{​​{1}},解析每个element的内容并将内容保存在element

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

Contructor:

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,这是正确的。

1 个答案:

答案 0 :(得分: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 "";
        }

    }