3

I would like to read an xml file. I' ve found an example which is good until the xml element doesn't have any attributes. Of course i've tried to look after how could I read attributes, but it doesn't works.

XML for example

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<car>
<properties>
<test h="1.12" w="4.2">
<colour>red</colour>
</test>
</properties>
</car>

Java Code:

public void readXML(String file) {
    try {

        File fXmlFile = new File(file);
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        doc = dBuilder.parse(fXmlFile);
        doc.getDocumentElement().normalize();

        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("test : "
                        + getTagValue("test", eElement));
                System.out.println("colour : " + getTagValue("colour", eElement));

            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

public String getTagValue(String sTag, Element eElement) {
    NodeList nlList = eElement.getElementsByTagName(sTag).item(0)
            .getChildNodes();


    Node nValue = (Node) nlList.item(0);
            System.out.println(nValue.hasAttributes());

    if (sTag.startsWith("test")) {
        return eElement.getAttribute("w");

    } else {
        return nValue.getNodeValue();
    }

}

Output:

false

test :

false

colour : red

My problem is, that i can't print out the attributes. How could i get the attributes?

2

4 Answers 4

5

There is alot wrong with your code; undeclared variables and a seemingly crazy algorithm. I rewrote it and it works:

import java.io.File;

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;

public final class LearninXmlDoc
{
    private static String getTagValue(final Element element)
    {
        System.out.println(element.getTagName() + " has attributes: " + element.hasAttributes());

        if (element.getTagName().startsWith("test"))
        {
            return element.getAttribute("w");

        }
        else
        {
            return element.getNodeValue();
        }
    }

    public static void main(String[] args)
    {
        final String fileName = "c:\\tmp\\test\\domXml.xml";

        readXML(fileName);
    }

    private static void readXML(String fileName)
    {
        Document document;
        DocumentBuilder documentBuilder;
        DocumentBuilderFactory documentBuilderFactory;
        NodeList nodeList;
        File xmlInputFile;

        try
        {
            xmlInputFile = new File(fileName);
            documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilder = documentBuilderFactory.newDocumentBuilder();
            document = documentBuilder.parse(xmlInputFile);
            nodeList = document.getElementsByTagName("*");

            document.getDocumentElement().normalize();

            for (int index = 0; index < nodeList.getLength(); index++)
            {
                Node node = nodeList.item(index);
                if (node.getNodeType() == Node.ELEMENT_NODE)
                {
                    Element element = (Element) node;

                    System.out.println("\tcolour : " + getTagValue(element));
                    System.out.println("\ttest : " + getTagValue(element));
                    System.out.println("-----");
                }
            }
        }
        catch (Exception exception)
        {
            exception.printStackTrace();
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

If you have a schema for the file, or can make one, you can use XMLBeans. It makes Java beans out of the XML, as the name implies. Then you can just use getters to get the attributes.

2 Comments

If you don't want to use XMLBeans, try castor or jibx. I generally blanket recommend any Apache project (even when, like XMLBeans, I have never used it).
thank you, but can you say any what is the problem with my code. to be honest i would like fix this. there is a getAttribute(String) method and i would like to know why get i null at elements, that actually has attribute :S
0

Use dom4j library.

InputStream is = new FileInputStream(filePath);

SAXReader reader = new SAXReader();
org.dom4j.Document doc = reader.read(is);
is.close();
Element content = doc.getRootElement();  //this will return the root element in your xml file
List<Element> methodEls = content.elements("element"); // this will retun List of all Elements with name "element"
Attribute attrib = methodEls.get(0).attribute("attributeName"); // this is the "attributeName" attribute of first element with name "element"

Comments

0

If you're looking purely to obtain attributes (E.g. a config / ini file) I would recommend using a java properties file.

http://docs.oracle.com/javase/tutorial/essential/environment/properties.html

If you just want to read a file create a new fileReader and put it into a bufferedReader.

BufferedReader in = new BufferedReader(new FileReader("example.xml"));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.