从XML文件中读取

时间:2013-11-10 18:29:34

标签: java xml file

我一直在努力寻找一种从Java中读取XML文件中特定数据的方法。我正在使用DOM和SAX。

我正在创建方法readLayoutFile(String areaName),程序将返回以下变量:varCheckedvarGeo[][]用于请求的区域。

我的问题是如何指定我想要checked的值,比如Triangle1。另外,如何调用位于Triangle1下的geometries下的所有坐标?

提前致谢。 /克里斯。

编辑:到目前为止,我只是设法读取整个XML文件中的大部分数据,远非我实际想做的事情:

        try {

        File fXmlFile = new File("C:\\Users/Chris/Desktop/layout1.xml");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile);
        doc.getDocumentElement().normalize();

        NodeList areaList = doc.getElementsByTagName("area");

        for (int i = 0; i < areaList.getLength(); i++) {

            Node areaNode = areaList.item(i);
            System.out.println();
            if (areaNode.getNodeType() == Node.ELEMENT_NODE) {

                Element areaElement = (Element) areaNode;

                System.out.println("Area Name : " + areaElement.getAttribute("name"));
                System.out.println("Checked : " + areaElement.getElementsByTagName("checked").item(0).getTextContent());

                NodeList geoList = doc.getElementsByTagName("geometries");
                for (int j = 0; j < geoList.getLength(); j++) {

                    NodeList geomList = doc.getElementsByTagName("geo");
                    Node geoNode = geomList.item(j);
                    if (geoNode.getNodeType() == Node.ELEMENT_NODE) {

                        Element geoElement = (Element) geoNode;
                        System.out.println("Geo Point " + (j+1) + ": " + geoElement.getAttribute("lat") + ", " + geoElement.getAttribute("long"));
                    }
                }
            }
        }
        } catch (Exception e) {
        e.printStackTrace();
        }

1 个答案:

答案 0 :(得分:2)

如果您希望将结构存储在内存中以进行重复查询,请使用JAXB将整个文档存储在Java POJO结构中。

如果是一次性的话,请使用SAX。这是查找条目的处理程序:

import java.util.ArrayList;
import java.util.Collection;

import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;

public class GeoFinder implements ContentHandler
{
    private final String areaName;

    private boolean capturing;
    private Collection<float[]> geoList;

    public GeoFinder(String areaName)
    {
        this.areaName = areaName;
    }

    public float[][] getGeoList()
    {
        if (geoList == null)
        {
            return null;
        }
        return geoList.toArray(new float[geoList.size()][]);
    }

    @Override
    public void characters(char[] ch, int start, int length) {}

    @Override
    public void endDocument() {}

    @Override
    public void endElement(String uri, String localName, String qName)
    {
        if ("area".equals(localName))
        {
            capturing = false;
        }
    }

    @Override
    public void endPrefixMapping(String prefix) throws SAXException {}

    @Override
    public void ignorableWhitespace(char[] ch, int start, int length) {}

    @Override
    public void processingInstruction(String target, String data) {}

    @Override
    public void setDocumentLocator(Locator locator) {}

    @Override
    public void skippedEntity(String name) {}

    @Override
    public void startDocument() {}

    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes atts)
    {
        if ("area".equals(localName))
        {
            if (areaName.equals(atts.getValue("name")))
            {
                capturing = true;
                geoList = new ArrayList<float[]>();
            }
        }
        else if ("geo".equals(localName) && capturing)
        {
            geoList.add(new float[]{
                    Float.parseFloat(atts.getValue("lat")),
                    Float.parseFloat(atts.getValue("long")),
            });
        }
    }

    @Override
    public void startPrefixMapping(String prefix, String uri) {}

}

用法:

XMLReader xmlReader = XMLReaderFactory.createXMLReader();
GeoFinder gf = new GeoFinder("Triangle1");
xmlReader.setContentHandler(gf);
InputStream is = new FileInputStream("C:\\Users/Chris/Desktop/layout1.xml");
try
{
    xmlReader.parse(new InputSource(is));
}
finally
{
    try
    {
        is.close();
    }
    catch (Throwable t)
    {
        t.printStackTrace();
    }
}
if (gf.getGeoList() == null)
{
    System.err.println("No area found");
}
else
{
    for (float[] e: gf.getGeoList())
    {
        System.out.println(e[0] + ", " + e[1]);
    }
}