2013-02-27 83 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); 
} 


    }