-1

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

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

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

提前致谢。/克里斯。

编辑:到目前为止,我只设法读取了整个 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();
        }
4

1 回答 1

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]);
    }
}
于 2013-11-10T19:00:33.877 回答