Reputation: 87
How can I get parent node value using xmlpullparser ?
<sample get="sample 1">
<child value="child a" />
<child value="child b" />
</sample>
<sample get="sample 2">
<child value="child c" />
<child value="child d" />
</sample>
code
if ( xml.getName().equals("child") ) {
String _value = xml.getAttributeValue(null, "value");
String parent = // GET PARENT NODE VALUE "sample"
}
Upvotes: 0
Views: 1341
Reputation: 25755
The XmlPullParser
is something like a StAX-parser. It allows for very fast (and small memory-footprint) parsing of documents.
The way it does that is by simply iterating over all elements in the XML-structure. It will then notify you when it found certain parts (like an opening/closing tag). These parser's are typically implemented top-down, meaning that you can't access any previous nodes.
If you need random access to all XML-nodes (including parent, parents parent, etc), you're better of reading the whole document into a DOM-tree and working with it. This takes up more memory, but is more flexible.
If you have to use the pull-parser, you could also store the previous values you're interested in, in temporary variables and access them somewhere down the line. Although, that's not part of the "original idea".
In your example, it could work like this:
if (xml.getName().equals("sample") {
this.lastParent = xml.getAttributeValue(null, "get"); // Store in class-field
} else if (xml.getName().equals("child") ) {
String _value = xml.getAttributeValue(null, "value");
String parent = this.lastParent;
}
Here, you save the parent value temporarily and use it when processing the children.
Upvotes: 2