How to get node attributes with Java SAX XML parser

Parsing XML from a String

import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
 
public class Main {
 
  public static void main(String[] args) throws Exception {
    // Prepare input stream
    String text = "<person number=\"72\"><name>Benny</name></person>";
 
    // Read input stream
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse(new InputSource(new StringReader(text)));
 
    // Output data
    NodeList elementsByTagName = document.getElementsByTagName("person");
    for (int i = 0; i &lt; elementsByTagName.getLength(); i++) {
      Node node = elementsByTagName.item(i);
      Element element = (Element) node;
      String attribute = element.getAttribute("number");
      System.out.println(attribute);
    }
  }
}

Parsing XML from a File

package com.welovecoding.parse.xml;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
 
public class Main {
 
  public static void main(String[] args) throws Exception {
    // Prepare input stream
    File file = new File("persons.xml");
    InputStream inputStream = new FileInputStream(file);
    Reader reader = new InputStreamReader(inputStream, "UTF-8");
    InputSource is = new InputSource(reader);
    is.setEncoding("UTF-8");
 
    // Read input stream
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse(is);
 
    // Output data
    NodeList elementsByTagName = document.getElementsByTagName("person");
    for (int i = 0; i < elementsByTagName.getLength(); i++) {
      Node node = elementsByTagName.item(i);
      Element element = (Element) node;
      String attribute = element.getAttribute("number");
      System.out.println(attribute);
    }
  }
}

Result

72

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.