这是我的xml文档,我试图使用DOMXmlParser来填充它..
< records>
<employee>
<name>Sachin Kumar</name>
<salary>50000</salary>
</employee>
<employee>
<name>Rahul Kumar</name>
<salary>60000</salary>
</employee>
<employee>
<name>John Mike</name>
<salary>70000</salary>
</employee>
< /records>
以下是OnCreate中的代码。
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = (TextView) findViewById(R.id.textView1);
try {
InputStream is = getAssets().open("file.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(is);
Element element = doc.getDocumentElement();
element.normalize();
NodeList nList = doc.getElementsByTagName("employee");
System.out.println("No Of Collected Objects" + nList.getLength() );
for (int i = 0; i < nList.getLength(); i++) {
Node node = nList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element2 = (Element) node;
tv1.setText(tv1.getText()+"\n\nFirstName : "
+ getValue("firstname",element2) + "\n");
tv1.setText(tv1.getText()+"\n\nMiddleName : "
+ getValue("middlename",element2) + "\n");
tv1.setText(tv1.getText()+"\n\nLastName : "
+ getValue("lastname",element2) + "\n");
tv1.setText(tv1.getText() + "Salary : "
+ getValue("salary",element2) + "\n");
tv1.setText(tv1.getText() + "-----------------------");
}
}
}
任何人都可以告诉以下代码中getChildNodes的用途以及为什么项索引应始终为0 ??
private static String getValue(String tag, Element element) {
NodeList nodeList = element.getElementsByTagName(tag).item(0)
.getChildNodes();
Node node = (Node) nodeList.item(0);
return node.getNodeValue();
}
答案 0 :(得分:0)
getChildNotes使用“tag”检索第一个元素的所有子节点的列表。
然后为节点分配返回列表中的第一个元素。