Reputation: 423
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?
Upvotes: 1
Views: 1202
Reputation: 423
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
Upvotes: 1
Reputation: 11085
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?
Upvotes: 0