0

我对解析 XML 文件有疑问。假设我有 XML 文件:

<line>
   <point>
      <X>100</X>
      <Y>100</Y>
   </point>
   <point>
      <X>200</X>
      <Y>200</Y>
   </point>
</line>

我想使用以下方法解析它DOM

    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(f);
    doc.getDocumentElement().normalize();
    NodeList nList = doc.getElementsByTagName("point");

    for (int temp = 0; temp < nList.getLength(); temp++) {

        Node nNode = nList.item(temp);

        if (nNode.getNodeType() == Node.ELEMENT_NODE) {

            Element eElement = (Element) nNode;

            System.out.println("x: " + eElement.getElementsByTagName("X").item(0).getTextContent());

但是 - 我怎样才能从 XML 文件中获取 X 和 Y 作为整数?- 第一个 X 作为 x1,第一个 Y 作为 y1,第二个 X 作为 x2,第二个 Y 作为 y2?

我试过了:

int x1 = Integer.valueOf(eElement.getAttribute("X"));
int y1 = Integer.valueOf(eElement.getAttribute("Y"));

但没有成功

4

1 回答 1

2
// Get the <line> element
NodeList nList = doc.getElementsByTagName("line");
Element line = (Element) nList.item(0);

// Get each <point> element from the <line>
Element point1 = (Element) line.getElementsByTagName("point").item(0);
Element point2 = (Element) line.getElementsByTagName("point").item(1);

// Get each <X> and <Y> from each <point> retrieved before
Integer x1 = Integer.parseInt(point1.getElementsByTagName("X").item(0).getTextContent());
Integer y1 = Integer.parseInt(point1.getElementsByTagName("Y").item(0).getTextContent());
Integer x2 = Integer.parseInt(point2.getElementsByTagName("X").item(0).getTextContent());
Integer y2 = Integer.parseInt(point2.getElementsByTagName("Y").item(0).getTextContent());

整个代码:

DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(f);
doc.getDocumentElement().normalize();

NodeList nList = doc.getElementsByTagName("line");

Element line = (Element) nList.item(0);

Element point1 = (Element) line.getElementsByTagName("point").item(0);
Element point2 = (Element) line.getElementsByTagName("point").item(1);

Integer x1 = Integer.parseInt(point1.getElementsByTagName("X").item(0).getTextContent());
Integer y1 = Integer.parseInt(point1.getElementsByTagName("Y").item(0).getTextContent());
Integer x2 = Integer.parseInt(point2.getElementsByTagName("X").item(0).getTextContent());
Integer y2 = Integer.parseInt(point2.getElementsByTagName("Y").item(0).getTextContent());

System.out.println("x1: " + x1 + "\ty1: " + y1 + "\tx2: " + x2 + "\ty2: " + y2);

输出:

x1: 100 y1: 100 x2: 200 y2: 200
于 2013-06-02T18:35:49.520 回答