1

I am using XMLDog for reading values from xml file. The problem is that I keep getting null values.

This is the xml file:

<?xml version="1.0" encoding="UTF-8"?>
<persons>
  <person>
    <name>John Doe</name>
    <age>30</age>
  </person>
  <person>
    <name>Jane Doe</name>
    <age>30</age>
  </person>
</persons>

And the code I am using:

final DefaultNamespaceContext nsContext = new DefaultNamespaceContext();
final XMLDog dog = new XMLDog(nsContext);

final Expression expression = dog.addXPath("/persons/person/name");
final XPathResults result = dog.sniff(new InputSource("/mnt/data-disk/persons.xml"));

final List<NodeItem> list = (List<NodeItem>)result.getResult(expression);
list.forEach(item -> System.out.println("Path: " + item.location + ", value: " + item.value));

This is what I am getting:

Path: /persons[1]/person[1]/name[1], value: null
Path: /persons[1]/person[2]/name[1], value: null

I need help figuring out why I get null for value.

In my project I need the exact path and value. Is there some other way of achieving this?

tomi
  • 373
  • 1
  • 5
  • 16
  • Weird that it has name[1]. I wonder if there is another way to specify the name that doesn't imply a list of items / matches? What happens if you make it /persons/person/@name ? – Kieveli Jan 25 '19 at 18:56
  • if the xPath is `/persons/person/@name` then the result list is empty – tomi Jan 25 '19 at 19:08

2 Answers2

1

XPath was missing: /text(). I've changed it to this: /persons/person/name/text(). The output is OK now:

Path: /persons[1]/person[1]/name[1]/text()[1], value: John Doe
Path: /persons[1]/person[2]/name[1]/text()[1], value: Jane Doe
tomi
  • 373
  • 1
  • 5
  • 16
0

From the documentation:

DOM Results

By default XMLDog does not construct dom nodes for results. You can configure for DOM results as follows:

import package jlibs.xml.sax.dog.sniff.Event;

Event event = dog.createEvent();
results = new XPathResults(event);
event.setListener(results);
event.setXMLBuilder(new DOMBuilder());
dog.sniff(event, new InputSource("note.xml"));

List<NodeItem> items = (List<NodeItem>)results.getResult(xpath1)

Is it possible that you're trying to loop over the DOM without the DOM having been created?

Kieveli
  • 10,944
  • 6
  • 56
  • 81