【问题标题】:XML parser exampleXML 解析器示例
【发布时间】:2011-12-18 00:38:04
【问题描述】:

我正在尝试解析以下 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”和每个“短名称”。我可以使用以下代码捕获短名称。但是,如何获取对应的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);
    }
  }
}

【问题讨论】:

  • 也许 XPath 在这里很适合你。

标签: java xml parsing


【解决方案1】:

id 值是 action 标签上的一个属性,所以一旦你在正确的节点,你会想通过类似的方式从它获取 id

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

【讨论】:

  • 很高兴它有帮助。欢迎投票和/或回答接受。
  • 我还没有足够的声望点来投票,但是一旦我得到它们,我会投票给你。谢谢。
  • @JohanneSmith - 你应该能够接受,我认为这会给你一些分数。您应该会看到一个检查,您可以点击我认为。
猜你喜欢
  • 2012-01-29
  • 1970-01-01
  • 2013-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-31
相关资源
最近更新 更多