XML解析器示例

时间:2011-10-29 22:12:28

标签: java xml parsing

我正在尝试解析以下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>

我想捕获每个“动作ID”和每个“短名称”。我可以使用以下代码捕获短名称。但是,您如何获得相应的操作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);
    }
  }
}

1 个答案:

答案 0 :(得分:7)

id值是action标签上的一个属性,所以一旦你在正确的节点上,你就会想要通过类似

的方式获取id。
String idValue = fstElmnt.getAttribute("id");