请帮我解析xml中给定xml的属性..
<tarifs>
<tarif type="internet" name="ОнЛайм 4" price="300" speedin="4" speedout="2"/>
<tarif type="internet" name="ОнЛайм 10" price="400" speedin="10" speedout="5"/>
<tarif type="internet" name="ОнЛайм 20" price="500" speedin="20" speedout="10"/>
</tarifs>
我已经打扰了这个
NodeList node = element.getElementsByTagName("tarif");
for (int j = 0; j < node.getLength(); j++) {
initialValues.put(TRAILER_ID, j);
initialValues.put(TRAILER_TITLE, node.item(j).ATTRIBUTE_NODE.getNamedItem("name").nodeValue);
}
但它不适合我..任何人都可以帮我解决这个问题
提前致谢
答案 0 :(得分:4)
尝试这种方式:
NodeList node = element.getElementsByTagName("tarif");
int length = node.getLength();
for (int j = 0; j < length; j++)
{
Element terrif = (Element) node.item(j);
String name = terrif.getAttribute("name");
initialValues.put(TRAILER_TITLE,name);
// and so on for other attributes...
}
答案 1 :(得分:0)
试试这个:
public void vParseXMLList(String sXMLResult)
{
org.xml.sax.helpers.DefaultHandler handler = new DefaultHandler()
{
boolean bIsMachineNameFound = false;
boolean bIsMachineSizeFound = false;
boolean bIsCreateDateFound = false;
boolean bIsMachineGUIDFound = false;
boolean bIsTimelinePasswordFound = false;
boolean bSHAPassword = false;
boolean bGUIDPassword = false;
public void startElement(String uri, String localName,String qName, Attributes attributes) throws SAXException
{
if (localName.equalsIgnoreCase("tarif")) {
if(attributes.getValue("type") != null){
String sType = attributes.getValue("type");
}
if(attributes.getValue("name") != null){
String sName = attributes.getValue("name");
}
if(attributes.getValue("price") != null){
int nPrice = Integer.parseInt(attributes.getValue("price"));
}
if(attributes.getValue("speedout") != null){
int nSpeedOut = Integer.parseInt(attributes.getValue("speedout"));
}
if(attributes.getValue("speedin") != null){
int nSpeedIn = Integer.parseInt(attributes.getValue("speedin"));
}
}
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
}
public void characters(char ch[], int start, int length) throws SAXException
{
}
};
SAXParserFactory saxParserFactory;
SAXParser saxParser;
InputStream inputStream;
try {
saxParserFactory = SAXParserFactory.newInstance();
saxParser = saxParserFactory.newSAXParser();
inputStream = new ByteArrayInputStream(sXMLResult.getBytes("UTF-8"));
saxParser.parse(inputStream, handler);
}
catch (UnsupportedEncodingException e) {}
catch (ParserConfigurationException e) {}
catch (SAXException e) {}
catch (IOException e) {}
finally
{
saxParserFactory = null;
saxParser = null;
inputStream = null;
}
}