我将使用 DOM 解析器在 java 中解析以下 xml 文件,但没有获取从我的 xml 文件中检索某些标签的信息,所以请帮我解决这个问题。
<policy name="DayCapturePolicy" type="capture">
<starttime>9:00:00 AM</starttime>
<endtime>9:00:00 PM</endtime>
<event name="NEW_APP_INSTALLED">
<eventFilter selectedAppName="Alarm"/>
<eventParam>selectedAppName</eventParam>
<eventParam>selectedAppVersion</eventParam>
<eventParam>appPackageName</eventParam>
<eventParam>appDirPath</eventParam>
</event>
</policy>
我想知道我应该如何从上面的 xml 文件中解析事件过滤器标记的值?我还想知道我应该如何从 eventParam 标记中检索所有值。我能够检索第一个标记 ieselectedAppName 的值但无法解析salectedAppVersion.appPackageName,appDirPath.的值提前谢谢
我曾尝试使用此代码进行解析。
NodeList nodeList = document.getElementsByTagName("policy");
Log.d("Reminder", "Number of Policies : "+nodeList.getLength());
for(int i=0;i<nodeList.getLength();i++){
Log.d("Reminder", "In 1");
//PolicyInfo policyInfo = new PolicyInfo();
Node node = nodeList.item(i);
NamedNodeMap namedNodeMap = node.getAttributes();
String policyName = namedNodeMap.getNamedItem("name").getNodeValue();
String policyType = namedNodeMap.getNamedItem("type").getNodeValue();
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) node;
Log.d("startTime : " ,""+ getTagValue("starttime", eElement));
Log.d("endtime : " ,""+ getTagValue("endtime", eElement));
NodeList nList = document.getElementsByTagName("event");
for(int j=0;i<nList.getLength();i++){
Log.d("Reminder", "In 1");
//PolicyInfo policyInfo = new PolicyInfo();
Node innerNode = nList.item(i);
NamedNodeMap innerNamedNodeMap = innerNode.getAttributes();
String eventName = innerNamedNodeMap.getNamedItem("name").getNodeValue();
Log.d("innerNode", eventName);
if(innerNode.getNodeType()== Node.ELEMENT_NODE){
Element innerElement = (Element) innerNode;
Log.d("eventParam : " ,""+ getTagValue("eventParam", innerElement));
Log.d("eventFilter : " ,""+ getTagValue("eventFilter", innerElement));
//Log.d("endtime : " ,""+ getTagValue("endtime", eElement));
}
//System.out.println("starttime : " + getTagValue("starttime", eElement));
// System.out.println("endtime: " + getTagValue("endtime", eElement));
//System.out.println("Nick Name : " + getTagValue("nickname", eElement));
//System.out.println("Salary : " + getTagValue("salary", eElement));
}
}
private static String getTagValue(String sTag, Element eElement) {
NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
Node nValue = (Node) nlList.item(0);
return nValue.getNodeValue();
}