2

I'm parsing an XML file with SAX and at some point I need the inner XML of an element. E.g., for the following XML

<a name="abc">
  <b>def</b>
<a>

I need to get the inner XML for the element a, which would be

<b>def<b>

What's the easiest way to do that?

Thanks.

Ivan

Ivan
  • 495
  • 3
  • 9
  • 20

1 Answers1

2

For this type of situation I suggest using 2 content handlers. The first is responsible for finding the relevant part of the document, and the second for processing the content. My answer to a similar question (see link below) demonstrates how to implement this approach:

Community
  • 1
  • 1
bdoughan
  • 147,609
  • 23
  • 300
  • 400
  • Great, thanks a lot. Just one more question. How to read the "pure XML code" with SAX? Should I reconstruct it (`startElement` reads the name of the element, `characters` reads the text inside...), or is there a better way? I want the other handler to take all the XML inside the element and return it as result. – Ivan Feb 17 '11 at 14:53
  • Ultimately it depends on what you want to do (could you provide more details?). Ultimately SAX just offers you the events and you need to process them accordingly. StAX is a similar API that you may find easy to work with as you can control when the events are fired (ultimately you get the same information). – bdoughan Feb 17 '11 at 15:09
  • I'm analyzing a WSLA document. I need to get the info from some important elements like `SLAParameter`, `ServiceLevelObjective` etc. Also, for some important elements (e.g., `metric`) i need to get both info about the element (i.e., attribute values) and the whole XML code of the element. – Ivan Feb 18 '11 at 09:07