我正在构建一个我必须解析XML
属性的应用程序。我的XML
看起来像这样:
<ad type="interstitial" animation="none">
<interstitial preload="0" autoclose="0" type="url" url="http://account.mobfox.com/activation_vad.php" orientation="portrait">
</interstitial>
</ad>
我尝试使用以下代码:
try {
XMLParser parser = new XMLParser();
xml = parser.getXmlFromUrl(URL);
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser parser1 = factory.newPullParser();
parser1.setInput(new StringReader(xml));
while (!"interstitial".equals(parser1.getName())
&& parser1.getEventType() != XmlPullParser.START_TAG) {
parser1.next();
}
Log.d("URL --> ", parser1.getAttributeValue(null, "url"));
} catch (Exception e) {
e.printStackTrace();
}
但是,我无法从属性中打印URL
。
我究竟做错了什么?任何形式的帮助将不胜感激。
答案 0 :(得分:0)
答案 1 :(得分:0)
试试这个..
Log.d("URL --> ", ""+parser1.getAttributeValue(null, "url"));
因为你在Log.d
空或 null
修改强>
URL url = new URL("Your URL");
DocumentBuilderFactory dbf = DocumentBuilderFactory
.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("ad");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("interstitial");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
System.out.println("Value : "
+ (nameElement.getAttribute("url")));
}