如何创建区域?

时间:2020-04-10 17:01:00

标签: java

import java.io.File;
import java.io.IOException;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

public class ReadXMLFile {
public static void main(String[] args) {

  SAXBuilder builder = new SAXBuilder();
  File xmlFile = new File("c:\\test.xml");

  try {

    Document document = (Document) builder.build(xmlFile);
    Element rootNode = document.getRootElement();
    List list = rootNode.getChildren("raum");

    for (int i = 0; i < list.size(); i++) {

       Element node = (Element) list.get(i);

       System.out.println("ID : " + node.getChildText("ID"));

    }

  } catch (IOException io) {
    System.out.println(io.getMessage());
  } catch (JDOMException jdomex) {
    System.out.println(jdomex.getMessage());
  }
}

}

我不明白为了将导入的坐标插入到多边形中,中间的步骤看起来如何。也许有人可以帮助我吗?

3 个答案:

答案 0 :(得分:2)

您可以按照任何示例JDOM解析器示例进行操作。 例如,this说明了如何读取xml并获取列表中的数据并对其进行迭代。只需按照以下步骤操作并了解您在做什么,就可以轻松完成。

答案 1 :(得分:1)

您可以阅读XML文件DOM解析器库检查this文章。

我假设您正在使用桌面应用程序,因此您可能希望使用FileChooser进行文件选择。这是example

此外,我认为您需要对XML文件进行一些结构上的更改(以方便起见),以便它具有以下内容:

<xpoints>
 <x>5<x/>
...
</xpoints>
<ypoints>
 <y>5<y/>
...
</ypoints>

但是对于现有的结构,做这样的事情将是永恒的:

    File file = new File("file");
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(file);
    doc.getDocumentElement().normalize();
    NodeList nodeList = doc.getElementsByTagName("edge");
// you can iterate over all edges
    for (int itr = 0; itr < nodeList.getLength(); itr++)
    {
      Node node = nodeList.item(itr);
      if (node.getNodeType() == Node.ELEMENT_NODE)
      {
        Element eElement = (Element) node;

//then you can access values, for example, to pass them to an array
        array.add(eElement.getElementsByTagName("x").item(0).getTextContent()));

      }
    }

答案 2 :(得分:1)

出于完整性考虑?
这是使用SAX解析器实现的方法。
请注意,从您的问题来看,我不清楚您指的是哪个Polygon。我认为这是一个Java类。它不能是java.awt.Polygon,因为它的点都是int,而您的示例XML文件仅包含double值。我想到的唯一另一个类是javafx.scene.shape.Polygon,它包含一个点数组,每个点都是double。因此,在下面的代码中,我创建了javafx.scene.shape.Polygon的实例。

对于您在问题中描述的情况,我看不到将整个DOM树加载到内存中的意义(没有双关语)。您只需在XML文件中每次遇到 x y 坐标时都创建一个点,并将这些坐标添加到点集合中。

这是代码。请注意,我创建了一个名为 polygon0.xml 的XML文件,其中包含您问题中的整个XML。另外请注意,您可以扩展类org.xml.sax.helpers.DefaultHandler而不是实现接口ContentHandler

import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

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

import javafx.scene.shape.Polygon;

public class Polygons implements ContentHandler {
    private boolean isX;
    private boolean isY;
    private Polygon polygon;
/* Start 'ContentHandler' interface methods. */
    @Override // org.xml.sax.ContentHandler
    public void setDocumentLocator(Locator locator) {
        // Do nothing.
    }

    @Override // org.xml.sax.ContentHandler
    public void startDocument() throws SAXException {
        polygon = new Polygon();
    }

    @Override // org.xml.sax.ContentHandler
    public void endDocument() throws SAXException {
        // Do nothing.
    }

    @Override // org.xml.sax.ContentHandler
    public void startPrefixMapping(String prefix, String uri) throws SAXException {
        // Do nothing.
    }

    @Override // org.xml.sax.ContentHandler
    public void endPrefixMapping(String prefix) throws SAXException {
        // Do nothing.
    }

    @Override // org.xml.sax.ContentHandler
    public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
        isX = "x".equals(qName);
        isY = "y".equals(qName);
    }

    @Override // org.xml.sax.ContentHandler
    public void endElement(String uri, String localName, String qName) throws SAXException {
        if (isX) {
            isX = false;
        }
        if (isY) {
            isY = false;
        }
    }

    @Override // org.xml.sax.ContentHandler
    public void characters(char[] ch, int start, int length) throws SAXException {
        if (isX || isY) {
            StringBuilder sb = new StringBuilder(length);
            int end = start + length;
            for (int i = start; i < end; i++) {
                sb.append(ch[i]);
            }
            polygon.getPoints().add(Double.parseDouble(sb.toString()));
        }
    }

    @Override // org.xml.sax.ContentHandler
    public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
        // Do nothing.
    }

    @Override // org.xml.sax.ContentHandler
    public void processingInstruction(String target, String data) throws SAXException {
        // Do nothing.
    }

    @Override // org.xml.sax.ContentHandler
    public void skippedEntity(String name) throws SAXException {
        // Do nothing.
    }
/* End 'ContentHandler' interface methods. */
    public static void main(String[] args) {
        Polygons instance = new Polygons();
        Path path = Paths.get("polygon0.xml");
        SAXParserFactory spf = SAXParserFactory.newInstance();
        try (FileReader reader = new FileReader(path.toFile())) { // throws java.io.IOException
            SAXParser saxParser = spf.newSAXParser(); // throws javax.xml.parsers.ParserConfigurationException , org.xml.sax.SAXException
            XMLReader xmlReader = saxParser.getXMLReader(); // throws org.xml.sax.SAXException
            xmlReader.setContentHandler(instance);
            InputSource input = new InputSource(reader);
            xmlReader.parse(input);
            System.out.println(instance.polygon);
        }
        catch (IOException                  |
               ParserConfigurationException |
               SAXException x) {
            x.printStackTrace();
        }
    }
}

这是运行上面的代码的输出:

Polygon[points=[400.3, 997.2, 400.3, 833.1, 509.9, 833.1, 509.9, 700.0, 242.2, 700.0, 242.2, 600.1, 111.1, 600.1, 111.1, 300.0, 300.0, 300.0, 300.0, 420.0, 600.5, 420.0, 600.5, 101.9, 717.8, 101.9, 717.8, 200.0, 876.5, 200.0, 876.5, 500.8, 1012.1, 500.8, 1012.1, 900.2, 902.0, 900.2, 902.0, 997.2], fill=0x000000ff]

编辑

根据OP的要求,这是使用JDOM(版本2.0.6)的实现

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.filter.ElementFilter;
import org.jdom2.input.SAXBuilder;
import org.jdom2.util.IteratorIterable;

import javafx.scene.shape.Polygon;

public class Polygon2 {
    public static void main(String[] args) {
        Polygon polygon = new Polygon();
        Path path = Paths.get("polygon0.xml");
        SAXBuilder builder = new SAXBuilder();
        try {
            Document jdomDoc = builder.build(path.toFile()); // throws java.io.IOException , org.jdom2.JDOMException
            Element root = jdomDoc.getRootElement();
            IteratorIterable<Element> iter = root.getDescendants(new ElementFilter("edge"));
            while (iter.hasNext()) {
                Element elem = iter.next();
                Element childX = elem.getChild("x");
                polygon.getPoints().add(Double.parseDouble(childX.getText()));
                Element childY = elem.getChild("y");
                polygon.getPoints().add(Double.parseDouble(childY.getText()));
            }
        }
        catch (IOException | JDOMException x) {
            x.printStackTrace();
        }
        System.out.println(polygon);
    }
}