【发布时间】:2015-06-23 22:17:46
【问题描述】:
我很难弄清楚如何解析这个数据块:
<prov version="1.1">
<characteristic type="section1">
<parm name="version" value="74"/>
<parm name="validity" value="172800"/>
</characteristic>
...
<characteristic type="section99">
<parm name="random_setting1" value="blahblah1"/>
<parm name="random_setting2" value="blahblah2"/>
<characteristic type="section99_subsection2">
<parm name="random_setting3" value="blahblah1"/>
<parm name="random_setting4" value="blahblah2"/>
</characteristic>
</characteristic>
</prov>
我在一个类似于上述示例的 xml 文件中可能有 200 多行。我想把它分成 4 个字段放入数据库中:
一级特征
二级特征(可以为空)
设置名称
价值
但我终其一生都无法弄清楚如何做到这一点。
我有这个文档生成器:
Log.d("RNM", "Starting xmlToDb");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document xmlParse = dBuilder.parse(new InputSource(new StringReader(xmlString)));
xmlParse.getDocumentElement().normalize();
NodeList nList = xmlParse.getElementsByTagName("characteristic");
for ( int tmp = 0; tmp < nList.getLength(); tmp++) {
Node nNode = nList.item(tmp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if ( nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
String charType = eElement.getAttribute("type"); //Tells me the value of characteristic
}
}
上面的工作是拉出所有的特征块并且可以得到值。但我不知道如何提取位于每个下方的 parmName 和 parmValud。
有任何处理这个问题的例子吗?我看了这里:http://theopentutorials.com/tutorials/android/xml/android-simple-xml-sax-parser-tutorial/ 但我不知道如何使用 saxparser 获取这些值。
【问题讨论】:
-
Rieekan,这让我走上了正轨,但缺少的是获取“嵌入式条目”的值(不确定它们被称为什么)是 xpp.getAttributeCount,然后循环遍历带有 getAttributeValue 的数字来构建我的 dbstring。当我从示例中获得每个特征部分所需的值时,next 和 nextToken 有助于继续前进。
标签: java android xml-parsing