0

我有一些存储在 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……

4

2 回答 2

2

假设您的 xml 文件是“c:/test.xml”

然后使用以下代码读取并按照您所说的格式放入哈希映射中
key=Roomnumber value=CoordLt,CoordLn

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.spi.DirStateFactory.Result;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


public class xml {
    public static void main(String[] args) 
    {
        HashMap<String,String>hMap=new HashMap<String, String>();
        File file=new File("c:/test.xml");

        if(file.exists())
        {
           DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
            try
            {
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document document=builder.parse(file);
                Element documentElement=document.getDocumentElement();
                NodeList sList=documentElement.getElementsByTagName("section");
                if (sList != null && sList.getLength() > 0)
                {
                    for (int i = 0; i < sList.getLength(); i++)
                    {
                        Node node = sList.item(i);
                        if(node.getNodeType()==Node.ELEMENT_NODE)
                        {
                            Element e = (Element) node;

                            NodeList nodeList = e.getElementsByTagName("Room");

                            String roomName= nodeList.item(0).getChildNodes().item(0)
                                            .getNodeValue();


                             nodeList = e.getElementsByTagName("CoordLt");
                            String coordValues= nodeList.item(0).getChildNodes().item(0)
                                            .getNodeValue();


                            nodeList = e.getElementsByTagName("CoordLn");
                            coordValues=coordValues+","+ nodeList.item(0).getChildNodes().item(0)
                                            .getNodeValue();
                            hMap.put(roomName, coordValues);
                        }
                    }
                }
            } catch(Exception e){
                System.out.println("exception occured");
            }
        }else
        {
            System.out.println("File not exists");
        }

    }
}
于 2012-08-06T13:16:10.007 回答
0

如果您使用此 xslt(可以在 Java 中完成)转换 XML,您将获得所需的输出,如果有人知道如何在 hashmap 中加载,您会没事的。

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:output method="text" indent="no" omit-xml-declaration ="yes" />

    <xsl:template match="/sections">
            <xsl:apply-templates select="section"/>
    </xsl:template>

  <xsl:template match="section" xml:space="default">
    <xsl:apply-templates select="Room"/>
    <xsl:text>:</xsl:text>
    <xsl:apply-templates select="CoordLt" />
    <xsl:text>,</xsl:text>
    <xsl:apply-templates select="CoordLn"/>
    <xsl:text>;</xsl:text>
  </xsl:template>

</xsl:stylesheet>
于 2012-08-06T10:19:53.670 回答