【发布时间】:2013-12-20 10:07:41
【问题描述】:
我真的希望你能帮助我解决这个问题...... 我需要从我的 xml 文件中获取特定数据,但我被困在某一点上,我无法弄清楚如何继续......
我想从网络中获取:网络名称; From Codes:mcc和mnc代码; From Settings:名称、id、类型、参数名称和值;
这就是我的xml文件的结构:
<country country="Andorra" isoCode="AD">
<networks>
<network name="Mobiland" isMNO="true" ranking="10">
<codes>
<code mcc="213" mnc="03" />
</codes>
<settings>
<setting alternativeName="Mobiland AD" ref="s1" name="IAP" id="2266" />
<setting alternativeName="Mobiland MMS AD" ref="s2" name="MMS" id="2265" />
</settings>
</network>
</networks>
<settings>
<setting id="s2" type="mmssetting">
<parameter name="mms-gprs-access-point-name" value="MMS" />
<parameter name="mms-gprs-name" value="MMS" />
<parameter name="mms-gprs-proxy" value="192.168.021.050" />
<parameter name="mms-gprs-proxy-port" value="9201" />
<parameter name="mms-url" value="http://mms.ad/mmsc" />
</setting>
<setting id="s1" type="iapsetting">
<parameter name="iap-gprs-access-point-name" value="internet" />
<parameter name="iap-gprs-name" value="Internet" />
<parameter name="iap-gprs-url" value="http://google.com" />
</setting>
</settings>
</country>
这是我到目前为止所拥有的......我真的无法继续......我在 String content = cNode.getLastChild().getTextContent().trim( );而且我不确定我的做法是否正确.....
public void ReadXML() 抛出 ParserConfigurationException、SAXException、 IOException {
// Get the DOM Builder Factory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// Get the DOM Builder
DocumentBuilder builder = factory.newDocumentBuilder();
// Load and Parse the XML document
// document contains the complete XML as a Tree.
Document document = builder.parse("D:\\test.xml");
List<Apn> empList = new ArrayList<Apn>();
// Iterating through the nodes and extracting the data.
NodeList nodeList = document.getDocumentElement().getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node instanceof Element) {
//Apn apn = new Apn();
System.out.println(node.getAttributes().getNamedItem("country")
.getNodeValue());
NodeList childNodes = node.getChildNodes();
for (int j = 0; j < childNodes.getLength(); j++) {
Node cNode = childNodes.item(j);
if (cNode instanceof Element) {
String content = cNode.getLastChild().getTextContent()
.trim();
switch (cNode.getNodeName()) {
case "networks":
System.out.println(content);
break;
case "setting":
System.out.println(content);
break;
case "codes":
System.out.println(content);
// emp.location = content;
break;
}
}
}
}
}
}
如有任何帮助,将不胜感激!
谢谢!
【问题讨论】:
-
也许 Castor 项目(一个 OXM 工具)可能对您的任务有用:castor.codehaus.org
-
你可以写一个xsd并在java对象中转换你的xml吗?
-
使用 trang 从您的 xml 生成架构文件。 peter-on-java.blogspot.in/2012/10/… 一旦你有了模式文件,你就可以使用 XMl-java 映射框架,如 jaxb 或 castor。一旦你生成了 java 类,你就可以使用这些 java 类将你的 xml 编组/解组为 java 对象,反之亦然。跨度>