3

Hi can anyone show me how I can read xml tags with their values with SimpleXML btw. I am building an android app.

I need to get all tags and values that are inside the root element:

<RootElement>
   <UnknownTab>UnkownValue</UnkownTab>
   <AnotherUnknownTab>UnkownValue</AnotherUnknownTab>
</RootElement>

The number of elements inside the RootElement is also unkown and can be different everytime.

UPDATE:

I am already using SimpleXml for every other serialization I am doing so i don't want to use another XML-parsing tool. The question is how to do this with SimpleXml and not how to serialize a xml.

UPDATE 2: I have reviewed the XML (its a bit complex) the definition is the following:

xsd-definition:

<element-sequence> 
   <element name="actualName" ..../>
   <element name="actualName" ..../>
   <element name="actualName" ..../>
   .
   .
   .
</element-sequence>

the size of element-sequence is variable and the tags of the elements inside the RootElement are the actualNames

<RootElement>
   <actualName>UnkownValue</actualName>
   <actualName>UnkownValue</actualName>
   .
   .
   .
</RootElement>

Is there any way to serialize this, if possible with SimpleXML

Wolfgang Fahl
  • 15,016
  • 11
  • 93
  • 186
Nickolaus
  • 4,785
  • 4
  • 38
  • 60
  • [XmlPullParser](http://developer.android.com/reference/org/xmlpull/v1/XmlPullParser.html) seems to be the way to go: http://developer.android.com/training/basics/network-ops/xml.html – sdabet Nov 13 '12 at 08:29

3 Answers3

0

You can use the SAXParser of Android to parse the String. The InputSource you need for the XMLReader of the Parser expects an input stream, so you have to convert your String into an input stream. You can use a ByteArrayInputStream for this:

InputStream is = new ByteArrayInputStream( myString.getBytes( charset ) );

See also:

Convert String into Strim

Android Parsing XML using SAX Parser

Community
  • 1
  • 1
Bhavik Ambani
  • 6,557
  • 14
  • 55
  • 86
0

Looks like this is impossible using SimpleXML, done the job using XPath.

Nickolaus
  • 4,785
  • 4
  • 38
  • 60
0

You might want to use a Visitor Strategy

The override "read" method:

@Override
public void read(Type type, NodeMap<InputNode> node) throws Exception {

gives you access to the NodeMap. With node.getNode() you can retrieve the actual current InputNode and e.g. query it's name and values. You might want to make sure that you have used "strict=false" in your RootElement annotation to make sure no Exception is thrown for non mapped tags.

Wolfgang Fahl
  • 15,016
  • 11
  • 93
  • 186