Dipu KS
Dipu KS

Reputation: 63

Parsing XML string

I am a newbie to Java world and struggling to parse a XML string that has attributes in them.

Can anyone help me how to parse this and get all the data? My XML string can change size depending on the NumOfParams.

Below is the XML:

<PictureManager>
   <FuncName>DisplayImage</FuncName>
   <NumOfParams>2</NumOfParams>
   <Parameters>
      <Param type="integer">10</Param>
      <Param type="String">C://Me.jpg</Param>
   </Parameters>
</PictureManager>

I need to be able to get "integer" and "String" attributes also from the XML. The XML string could grow or shrink based on the <NumOfParams>

It will help a lot if you can post some code that actually creates a XML string with the above mentioned tags.

Thanks in advance.

Upvotes: 1

Views: 154

Answers (2)

Eric
Eric

Reputation: 1291

My suggestion is starting from the basic step:

First, you probably need to think about your xml file connection: url? local? Second, you need to instance a DocumentBuilderFactory and a builder

DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();

OR

URLConnection conn = new URL(url).openConnection(); InputStream inputXml = conn.getInputStream();

DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance() .newDocumentBuilder(); Document xmlDoc = docBuilder.parse(inputXml);

The Next step is Parsing XML file:

Document xmlDom = dBuilder.parse(xmlFile);

After that, it turns a xml file into DOM or Tree structure, and you have to travel a node by node to get Attributes or Content. In your case, you need to get content. Here is an example:

String getContent(Document doc, String tagName){
        String result = "";

        NodeList nList = doc.getElementsByTagName(tagName);
        if(nList.getLength()>0){
            Element eElement = (Element)nList.item(0);
            String ranking = eElement.getTextContent();
            if(!"".equals(ranking)){
                result = String.valueOf(ranking);
            }

        }
        return result;
    }

return of the getContent(xmlDom,"NumOfParams") is "2".

After you can parse simple xml file, you could try to travel all the xml file and print it out. Then get touch with SAX or JAXB.

Good luck

Upvotes: 1

libik
libik

Reputation: 23029

In java libraries exist with methods for parsing XML document. For example this :

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputSource xml = new InputSource();
    xml.setCharacterStream(xmlSTring);
    Document doc = db.parse(xml);
    NodeList nodes = doc.getElementsByTagName("PictureManager");

    // iterate objects 
    for (int i = 0; i < nodes.getLength(); i++) {
       Element element = (Element) nodes.item(i);
       .
       .
       .
    }

Upvotes: 1

Related Questions