我有一些存储在 XML 中的信息,我需要解析 XML 并将一些值存储在 Hashmap 中。这是 XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<sections xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<section ID="1">
<Room>Room1</Room>
<Capactiy>25</Capactiy>
<Approval_Mode>personally</Approval_Mode>
<Building>Building1</Building>
<Address>Streer, 1. Stock, links</Address>
<Room_Number>ZA0115</Room_Number>
<CoordLt>16.412094</CoordLt>
<CoordLn>48.19719</CoordLn>
</section>
<section ID="2">
<Room>Room2</Room>
<Capactiy>120</Capactiy>
<Institute>E401</Institute>
<Approval_Mode>personally</Approval_Mode>
<Building>Building2</Building>
<Address>Street 2, Building2, Stiege 7, 1.Stock</Address>
<Room_Number>AH0105</Room_Number>
<CoordLt>16.369865</CoordLt>
<CoordLn>48.199006</CoordLn>
</section>
----
我希望该键为:Room1 和值:16.412094,48.19719(Section ID=1 的示例)
这是第一部分的示例。我有 100 多个部分,所以我想为每个部分存储键和值,就像我在第一个示例中解释的那样。
输出将是:
房间1:16.412094,48.19719;房间2:16.369865,48.199006;
房间3:16,48;. . . 100 室:16,49;
谁能帮我?
这是我的代码:
import java.io.File;
import java.sql.ResultSet;
import java.util.HashMap;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
public class XML extends DefaultHandler
{
static HashMap<StringBuffer, String> hashMap;
String elementName;
StringBuffer elementValue;
private HashMap<String, String> newMap;
public static void main(String[] args)
{
DefaultHandler handler = new XML();
SAXParserFactory factory = SAXParserFactory.newInstance();
try
{
hashMap = new HashMap<StringBuffer, String>();
//out = new OutputStreamWriter(System.out, "UTF8");
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(new File("xml1.xml"), handler);
System.out.println(hashMap);
}
catch(Throwable t)
{
t.printStackTrace();
}
System.exit(0);
}
public void startElement(String namespaceURI, String sName, String qName, Attributes attrs)
throws SAXException
{
String eName = sName;
if("".equals(eName)) eName = qName;
elementName = eName;
if(attrs != null)
{
for(int i = 0; i < attrs.getLength(); i++)
{
String aName = attrs.getLocalName(i);
if("".equals(aName)) aName = attrs.getQName(i);
}
}
}
public void endElement(String namespaceURI, String sName, String qName)
throws SAXException
{
String eName = sName;
if("".equals(eName)) eName = qName;
if(eName.equals(elementName))
hashMap.put(elementValue,""+ elementName );
elementValue = null;
}
public void characters(char[] ch, int start, int length)
throws SAXException
{
String str = new String(ch, start, length);
if(elementValue == null)
elementValue = new StringBuffer(str);
else
elementValue.append(str);
}
}
使用此代码,我无法获得所需的输出。输出为:Room=Room1,容量=25……