2013-02-27 357 views
1

的XML文件我已經在我的Android內部存儲保存到服務器的IP配置在/Simulate/Configuration.xml一個XML文件閱讀android系統

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。

+1

你不必安德烈Voitenkov暗示的回答'ipAddress'或'port'在XML屬性。你有價值。 – 2013-02-27 10:16:43

+0

您可以將其發佈爲答案 – Giz 2013-02-27 10:43:11

+0

b.w謝謝=) – Giz 2013-02-27 10:43:28

回答

0

,因爲我已經使用的元素和屬性不:)

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


    }