您可以使用Java的DOM api進行xml處理和xpath。
下面是一些示例代碼,做你想要什麼部分(提取IP和端口)。您將需要修改它做休息:
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class DomTester {
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
InputStream inStr = null;
try {
String xml = "<?xml version=\"1.0\"?>"
+ "<Database>"
+ "<DB>"
+ "<ip>666</ip>"
+ "<port>7</port>"
+ "</DB>"
+ "<DB>"
+ " <ip>13</ip>"
+ "<port>1</port>"
+ "</DB>"
+ "</Database>";
inStr = new ByteArrayInputStream(xml.getBytes());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(inStr);
XPathFactory xFactory = XPathFactory.newInstance();
XPath xpath = xFactory.newXPath();
XPathExpression expr = xpath.compile("/Database");
Element databaseEl = (Element)expr.evaluate(doc, XPathConstants.NODE);
NodeList databaseNodeList = databaseEl.getChildNodes();
for (int ii=0; ii<databaseNodeList.getLength(); ++ii) {
Node dbNode = databaseNodeList.item(ii);
XPathExpression ipExpr = xpath.compile("ip");
Element ipElement = (Element)ipExpr.evaluate(dbNode, XPathConstants.NODE);
String ip = ipElement.getTextContent();
XPathExpression portExpr = xpath.compile("port");
Element portEl = (Element)portExpr.evaluate(dbNode, XPathConstants.NODE);
String port = portEl.getTextContent();
System.out.println("DB node[" + ii + "] = ip: " + ip + " port: " + port);
}
} finally {
if (null != inStr) {
inStr.close();
}
}
}
}
因爲你是從文件中讀取,而不是使用字符串,而不是做這樣的:
inStr = new ByteArrayInputStream(xml.getBytes());
做到這一點:
File f = new File("your/file/path.xml");
inStr = new FileInputStream(f);