Question

I have the following in my xml file and basically I am trying to change an attribute of the xml document

    <?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <root level="DEBUG">
  </root>
</configuration>

This is my java file

    public static void changeXMLLogLevel(String pathToXMLDocument, String newWarnLevel){
    // make sure that xml file is present
    File f = new File(pathToXMLDocument);

    if (f.exists()) {
        try {
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(pathToXMLDocument);


            // Get the warn level
            Node warnLevel = doc.getElementsByTagName("root").item(0);

            System.out.println("The warn level is: " + warnLevel);

           // more code..................

For some reason the warn level is null although I have a tag in my xml document called root.

This is what I get for my output The warn level is: [root: null]

Was it helpful?

Solution

I think you misunderstand your output. With this

Node warnLevel = doc.getElementsByTagName("root").item(0);

you get the single root tag in your xml. The toString() of that object is the name of the tag and the node's value, but apparently it always returns null for element nodes.

What you want is to get the attribute level.

Node warnLevel = doc.getElementsByTagName("root").item(0).getAttributes().getNamedItem("level");
System.out.println("The warn level is: " + warnLevel);

which prints

level="DEBUG"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top