0

I have this data in the xml file:

<manufacturer>Audi</manufacturer>
    <model>Q3</model>
    <production-year>2011</production-year>
    <horsepower>150</horsepower>
    <consumption type="fuel">7.6</consumption>
    <price>36430</price>

And I wrote the following code that lets me read all the nodes from the file.

DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = null;
            try {

                builder = builderFactory.newDocumentBuilder();

                Document document = builder.parse(new File(fileName));

                Element rootElement = document.getDocumentElement();

                NodeList nodes = rootElement.getChildNodes();
                for (int i = 0; i < nodes.getLength(); i++) {
                    Node node = nodes.item(i);

                    if (node instanceof Element) {
                        Element car = (Element) node;

                        String id = car.getAttribute("id");
                        String manufacturer = car.getElementsByTagName("manufacturer").item(0).getTextContent();
                        String model = car.getElementsByTagName("model").item(0).getTextContent();
                        String production_year = car.getElementsByTagName("production-year").item(0).getTextContent();
                        String hp = car.getElementsByTagName("horsepower").item(0).getTextContent();
                        **String type = "";**
                        String fuelConsm = car.getElementsByTagName("consumption").item(0).getTextContent();
                        String price = car.getElementsByTagName("price").item(0).getTextContent();

My question is how do I read the value of the attribute type="" in the xml file and get it as a String?

Thanks in advance.

  • 1
    https://stackoverflow.com/a/5895228/14419 – Mads Hansen Jan 29 '22 at 15:02
  • It returns an empty String when I do it like that. – Danilo Djurovic Jan 29 '22 at 17:14
  • fwif, this is a lot of code to parse a bit of xml. I would suggest you have a look at simplexml. Its premise is that you create a class with the right annotations to allow it parse your xml directly into a coherent java object tree. You just give it the annotated object schema, it then does all the parsing. It handles attributes too. – Dmytro Bugayev Jan 29 '22 at 20:50

1 Answers1

2

I used this to get the needed result.

Node typeNode = car.getElementsByTagName("consumption").item(0);
String type = "Type : " + ((Element) typeNode).getAttribute("type");