1

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

配置.xml

<?xml version="1.0"?>

<IPconfig>

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

</IPconfig>

访问ip地址和端口号的代码

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 时都返回一个空值。如何从 xml 中获取 ipaddress 和 port 值?任何帮助表示赞赏。另外,如果有更好的方法来指定服务器的 ipconfig。

4

2 回答 2

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


    }
于 2013-02-27T10:45:52.577 回答
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);
于 2013-02-28T08:38:07.450 回答