在android中读取xml文件

时间:2013-02-27 10:12:38

标签: android xml-parsing data-storage

我已将服务器的IP配置保存在我的android内部存储中的/Simulate/Configuration.xml中的xml文件中

configuration.xml文件

<?xml version="1.0"?>

<IPconfig>

<ipAddress>172.**.***.***</ipAddress>
<port>5000</port>

</IPconfig>

访问ipaddress和端口号的代码

try {
File sdcard = Environment.getExternalStorageDirectory ();
File FXmlFile = new File (sdcard, "/ Simulate / Configuration.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement (). normalize ();
NodeList nlist = doc.getElementsByTagName ("IPconfig");
for (int temp = 0; temp <nList.getLength (); temp + +) {
Node nNode = nList.item(temp);
if (nNode.getNodeType () == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
SERVERIP= eElement.getAttribute("ipAddress");
System.out.println ("server ip:" + SERVERIP);
SERVERPORT= eElement.getAttribute("port");
System.out.println ("Server port:" + ServerPort);
}
}
}catch (Exception e) {
            e.printStackTrace();
            }

当我打印SERVERIP和SERVERPORT时,都返回null。如何从xml获取ipaddress和端口值?任何帮助表示赞赏。另外,如果有更好的方法来指定服务器的ipconfig。

2 个答案:

答案 0 :(得分:0)

    import org.xml.sax.Attributes;
    import org.xml.sax.SAXException;
    import org.xml.sax.helpers.DefaultHandler;


    public class Handler extends DefaultHandler
    {
public String ipAddress;
public String port;
public StringBuffer  sbBuffer;

@Override
public void startElement(String uri, String localName, String qName,
        Attributes attributes) throws SAXException {
    // TODO Auto-generated method stub
    sbBuffer = new StringBuffer();
}

@Override
public void endElement(String uri, String localName, String qName)
        throws SAXException {
    if(localName.equalsIgnoreCase("ipAddress"))
        ipAddress = sbBuffer.toString();
    else if(localName.equalsIgnoreCase("port"))
        port = sbBuffer.toString();
}

public void characters(char[] ch, int start, int length) throws SAXException
{
    sbBuffer.append(ch,start,length);
}


    }

答案 1 :(得分:0)

由于Andrey Voitenkov暗示我使用了元素而不是属性,因此回答:)

********EDIT*******
SERVERIP= eElement.getElementsByTagName("ipAddress").item(0).getTextContent();
System.out.println("server    ip:"+SERVERIP);
SERVERPORT= eElement.getElementsByTagName("port").item(0).getTextContent();
System.out.println("server port:"+SERVERPORT);