我想解析一個xml文件(來自資產),但是我無法正確理解它。用Android中的屬性解析XML
通常當我做到這一點,我會格式化像下面的我的XML文件:
<channel>
<item>
<name>Hello Earth</name>
<place>Earth</place>
</item>
<item>
<name>Goodbye Mars</name>
<place>Mars</place>
</item/>
</channel>
而且我會用下面的代碼分析出什麼,我需要:
AssetManager assetManager = getAssets();
InputStream inputStream = assetManager.open("words.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setCoalescing(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document dom = builder.parse(inputStream);
org.w3c.dom.Element root = dom.getDocumentElement();
NodeList items = root.getElementsByTagName("item");
String name="";
String place="";
for (int i = 0; i < items.getLength(); i++) {
Node item = items.item(i);
NodeList properties = item.getChildNodes();
for (int j = 0; j < properties.getLength(); j++) {
Node property = properties.item(j);
String propertyName = property.getNodeName();
if (propertyName.equalsIgnoreCase("name")) {
String strText = property.getFirstChild()
.getNodeValue();
nam = strText;
}
if (propertyName.equalsIgnoreCase("place")) {
String strText = property.getFirstChild()
.getNodeValue();
place = strText;
}
db.insertWord(name, place);
}
然而, xml來自另一個源,它的格式不同,它使用屬性,因爲它是一個mysql導出。這是我必須解析XML,但我無法弄清楚如何,我應該這樣,我試着用的getAttribute玩弄()方法,但不能獲取數據了XML的:
<table name="item">
<column name="name">Hello Earth</column>
<column name="place">Earth</column>
</table>
<table name="item">
<column name="name">Goodbye Mars</column>
<column name="place">Mars</column>
</table>
謝謝你,這真的幫助我 – brux