Johanne Smith
Johanne Smith

Reputation: 75

XML parser example

I am trying to parse the following XML:

<?xml version="1.0" encoding="UTF-8"?>
<!-- _tag -->
<tag value="0" actions_tagged="0" name="adjust temperature">
  <link type="application/xml" rel="list" href="/api/v1/tags.xml"/>
  <link type="application/xml" rel="self" href="/api/v1/tags/adjust%20temperature.xml"/>
  <actions>
    <action id="105">
      <link type="application/xml" rel="tagged_action" href="/api/v1/actions/105.xml"/>
      <short_name>Set thermostat to 68F in the winter and 74F in the summer</short_name>
    </action>
    <action id="106">
      <link type="application/xml" rel="tagged_action" href="/api/v1/actions/106.xml"/>
      <short_name>Close windows and blinds</short_name>
    </action>
  </actions>
</tag>

I would like to capture each "action id" and each "short name". I'm able to capture the short name with the following code. But, how do you obtain the corresponding action id?

String action = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Actions myActions  = new Actions();
InputSource inStream = new InputSource();
inStream.setCharacterStream(new StringReader(xml));

Document doc = db.parse(inStream);
NodeList nodeList = doc.getElementsByTagName("action");

for (int s = 0; s < nodeList.getLength(); s++) {
  Node fstNode = nodeList.item(s);
  if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
    Element fstElmnt = (Element) fstNode;

    NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("short_name");
    Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
    NodeList lstNm = lstNmElmnt.getChildNodes();
    String currentAction = ((Node) lstNm.item(0)).getNodeValue();
    if(currentAction != null) {
      myActions.setShort_name(currentAction);
    }

    lstNmElmntLst = fstElmnt.getElementsByTagName("action id"); 
    // this didn't work - nor did 'id'
    lstNmElmnt = (Element) lstNmElmntLst.item(0);
    lstNm = lstNmElmnt.getChildNodes();
    currentAction = ((Node) lstNm.item(0)).getNodeValue();
    if(currentAction != null) {
      myActions.setDescription(currentAction);
    }
  }
}

Upvotes: 2

Views: 7783

Answers (1)

Don Roby
Don Roby

Reputation: 41137

The id value is an attribute on the action tag, so once you're at the proper node, you'll want to get the id from it by something like

String idValue = fstElmnt.getAttribute("id"); 

Upvotes: 7

Related Questions