2
我是XML解析的新手。我已閱讀關於DOM和SAX解析器,並嘗試了幾個示例實現。然而,我無法解析以下XML數據解析XML並獲取標籤內的值屬性值
<?xml version="1.0" ?>
<collection>
<action value="submit"/>
<protocol_version value="1"/>
<reponse value="Success"/>
<batch>
<sample>
<count value="1"/>
<count2 value="2"/>
<count3 value="3"/>
</sample>
<sample_2>
<date value="10/10/2010"/>
<page value="SampleData"/>
<track value="123123123"/>
<same value="1.00"/>
<data>
<first_name value="Jeffrey"/>
<SSID value="1231231231"/>
<last_name value="Chuckle"/>
<field1 value="123123123"/>
<field2 value="Sam E. Bonzella"/>
<field3 value="SOME VALUE"/>
<field4 value="SOME VALUE 2"/>
<field5 value="TEXT"/>
<field6 value="12312"/>
</data>
</sample_2>
</batch>
</collection>
下面是示例代碼我試圖實現,但它需要但卻難免重複代碼,同時也中,數據是沒有組織。我也嘗試過JAXB解析器,但無法獲取值屬性。
public class test {
public static void main(String[] args){
try {
File inputFile = new File("staff.xml");
DocumentBuilderFactory dbFactory
= DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
System.out.println("Base :"
+ doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("action");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("Element :"
+ nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("Action : "
+ eElement.getAttribute("value"));
}
}
nList = doc.getElementsByTagName("transaction_count");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("Element :"
+ nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("transaction_count : "
+ eElement.getAttribute("value"));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
理想情況下,我希望將數據解析爲數組或可能是Map。